标签:
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\n",bfs()); 60 } 61 return 0; 62 }
挑战程序设计迷宫最短路径模板
标签:
原文地址:http://www.cnblogs.com/WDKER/p/5388167.html