这有一个迷宫,有0~8行和0~8列:
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
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
-
输入
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
- 输出最少走几步。 样例输入
-
2 3 1 5 7 3 1 6 7
样例输出
-
12
11
-
#include<iostream> #include<cstdio> #include<queue> #include<cstring> using namespace std; 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[10][10]; int sx,sy,ex,ey; struct node{ int x; int y; int stemp; }u,e; int text(node a){ // printf("a.x=%d a.y=%d\n",a.x,a.y); // printf("m=%d\n",Map[a.x][a.y]); if(a.x>0 && a.y<9 && a.x<9 &&a.y>0){ if(Map[a.x][a.y]==0) return 1; else return 0; } else return 0; } int BFS(){ queue<node>q; while(!q.empty()) q.pop(); memset(book,0,sizeof(book)); int next[4][2]={ {0,1},{1,0},{0,-1},{-1,0} }; int k; u.x=sx; u.y=sy; u.stemp=0; q.push(u); book[u.x][u.y]=1; while(!q.empty()){ u=q.front(); q.pop(); // printf("C x=%d y=%d\n",u.x,u.y); if(u.x==ex &&u.y==ey){ printf("%d\n",u.stemp); break; } for(k=0;k<4;k++){ e.x=u.x+next[k][0]; e.y=u.y+next[k][1]; e.stemp=u.stemp+1; // printf(" ex=%d ey=%d\n",e.x,e.y); // printf("t=%d b=%d\n",text(e),book[e.x][e.y]); if(text(e)==1 && book[e.x][e.y]==0){ q.push(e); // printf("R x=%d y=%d\n",e.x,e.y); book[e.x][e.y]=1; } } } } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d%d%d%d",&sx,&sy,&ex,&ey); BFS(); } }