1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 using namespace std; 5 6 int d[9][9]; //标记此点是否访问并记录距离 7 int maze[9][9]={ 8 1,1,1,1,1,1,1,1,1, 9 1,0,0,1,0,0,1,0,1, 10 1,0,0,1,1,0,0,0,1, 11 1,0,1,0,1,1,0,1,1, 12 1,0,0,0,0,1,0,0,1, 13 1,1,0,1,0,1,0,0,1, 14 1,1,0,1,0,1,0,0,1, 15 1,1,0,1,0,0,0,0,1, 16 1,1,1,1,1,1,1,1,1}; 17 const int INF=1<<10; 18 typedef pair<int ,int> P; 19 int n,sx,sy,gx,gy; 20 int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; 21 22 int bfs() 23 { 24 memset(d,0,sizeof(d)); 25 queue<P> que; 26 for(int i=0;i<9;i++) 27 for(int j=0;j<9;j++) 28 d[i][j]=INF; 29 que.push(P(sx,sy)); 30 d[sx][sy]=0; 31 32 while(!que.empty()) 33 { 34 P p=que.front(); 35 que.pop(); 36 if(p.first==gx&&p.second==gy) 37 break; 38 39 for(int i=0;i<4;i++) 40 { 41 int nx=p.first+dx[i],ny=p.second+dy[i]; 42 43 if(0<=nx&&nx<=8&&0<=ny&&ny<=8&&maze[nx][ny]==0&&d[nx][ny]==INF) //当前位置是否可以加入 44 { 45 que.push(P(nx,ny)); 46 d[nx][ny]=d[p.first][p.second]+1; 47 } 48 } 49 } 50 return d[gx][gy]; 51 } 52 53 int main() 54 { 55 scanf("%d",&n); 56 while(n--) 57 { 58 scanf("%d%d%d%d",&sx,&sy,&gx,&gy); 59 printf("%d ",bfs()); 60 } 61 return 0; 62 }
挑战程序设计迷宫最短路径模板
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 using namespace std; 5 6 int d[9][9]; //标记此点是否访问并记录距离 7 int maze[9][9]={ 8 1,1,1,1,1,1,1,1,1, 9 1,0,0,1,0,0,1,0,1, 10 1,0,0,1,1,0,0,0,1, 11 1,0,1,0,1,1,0,1,1, 12 1,0,0,0,0,1,0,0,1, 13 1,1,0,1,0,1,0,0,1, 14 1,1,0,1,0,1,0,0,1, 15 1,1,0,1,0,0,0,0,1, 16 1,1,1,1,1,1,1,1,1}; 17 //typedef pair<int ,int> P; 18 struct node{ 19 int x,y,c; 20 }; 21 int n,sx,sy,gx,gy; 22 int vis[9][9]; //判断是否访问了 23 int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; 24 25 int bfs() 26 { 27 memset(vis,0,sizeof(vis)); 28 node ee,e1; 29 ee={sx,sy,0}; 30 vis[sx][sy]=1; 31 queue<node> q; 32 q.push(ee); 33 while(!q.empty()) 34 { 35 ee=q.front(); 36 q.pop(); 37 if(ee.x==gx&&ee.y==gy) 38 break; 39 for(int i=0;i<4;i++) 40 { 41 int nx=ee.x+dx[i],ny=ee.y+dy[i]; 42 if(nx>=0&&nx<=8&&ny>=0&&ny<=8&&maze[nx][ny]==0&&vis[nx][ny]==0) 43 { 44 e1.x=nx;e1.y=ny;e1.c=ee.c+1; 45 q.push(e1); 46 vis[nx][ny]=1; 47 } 48 } 49 } 50 return ee.c; 51 } 52 53 int main() 54 { 55 scanf("%d",&n); 56 while(n--) 57 { 58 scanf("%d%d%d%d",&sx,&sy,&gx,&gy); 59 printf("%d ",bfs()); 60 } 61 return 0; 62 }
原先写的,写完上面之后,知道自己错在判断条件上。