bfs,dfs

#include
#define M 7
int map[M][M];
int book[M][M];
int dfs(int x, int y, int step)
{
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
    int nx,ny,k,t;
    for(k=0; k<4; k++){
        nx=x+next[k][0];
        ny=y+next[k][1];
        //判断是否越界
        if(x>=M || y>=M || x<0 || y<0){
            continue;
        }
        //判断是否可走
        if(map[nx][ny]==0){
            //判断是否到达终点
            if(nx==4 && ny==6){
                book[x][y]=step;
                return 1;
            }
            map[nx][ny]=1;//标记已走
            t=dfs(nx,ny,step+1);
            if(t)
                book[nx][ny]=step;
            return 1;
        }
    }
    return 0;
}
int main(void)
{
    int sx,sy;
    int i,j;
    //读入起始位置
    scanf("%d%d", &sx, &sy);
    //读入地图
    for(i=0; i
#include
#include
typedef struct Node{
  int x;
  int y;
  int f;
  int s;
}node;
int map[9][9]=
{
 1,1,1,1,1,1,1,1,1,
 1,0,0,1,0,0,1,0,1,
 1,0,0,1,1,0,0,0,1,
 1,0,1,0,1,1,0,1,1,
 1,0,0,0,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,0,0,0,1,
 1,1,1,1,1,1,1,1,1
};
int book[9][9];
int next[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int head=1;
int tail=1;

int main()
{
  node que[81];
  int flag=0;

  int n;
  scanf("%d",&n);
  int i,j,k;
  for(i=0; i8 || ty<0 || ty>8)
          continue;
        if(map[tx][ty]==0 && book[tx][ty]==0){
          book[tx][ty]=1;
          que[tail].x=tx;
          que[tail].y=ty;
          que[tail].f=head;
          que[tail].s=que[head].s+1;
          tail++;
        }
        if(tx==c && ty==d){
          flag=1;
        }
      }

      if(flag==1)
        break;
      head++;
    }
    printf("%d\n",que[tail-1].s);
  }
  return 0;
}

你可能感兴趣的:(bfs,dfs)