最少步数
时间限制:65535 KB
难度:4
- 描述
-
这有一个迷宫,有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,10表示道路,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
代码一:写的复杂了View Code1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 5 using namespace std; 6 7 #define N 9 8 9 int maze[N][N]={1,1,1,1,1,1,1,1,1, 10 1,0,0,1,0,0,1,0,1, 11 1,0,0,1,1,0,0,0,1, 12 1,0,1,0,1,1,0,1,1, 13 1,0,0,0,0,1,0,0,1, 14 1,1,0,1,0,1,0,0,1, 15 1,1,0,1,0,1,0,0,1, 16 1,1,0,1,0,0,0,0,1, 17 1,1,1,1,1,1,1,1,1}; 18 int mazeH[N][N]; 19 20 struct Node 21 { 22 int x,y,cnt; 23 24 }; 25 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//定义方向 26 27 bool Judge(int x,int y) 28 { 29 return (x < N && x >= 0 && y < N && y >= 0 && !mazeH[x][y])?true:false;//如果没有超出边界,返回true,否者false 30 31 } 32 33 void MakeNode(int x,int y,int cnt,Node &node) 34 { 35 node.x=x; 36 node.y=y; 37 node.cnt=cnt; 38 mazeH[x][y]=1; 39 } 40 41 int bfs(int sX,int sY,int eX,int eY) 42 { 43 Node node,tempNode; 44 MakeNode(sX,sY,0,node); 45 queue<Node> Q; 46 Q.push (node); 47 while( !Q.empty() ) 48 { 49 node=Q.front(); 50 Q.pop (); 51 if( node.x==eX && node.y==eY )//判断是否找到结束的那个点,如果找到了,将返回最小步数; 52 { 53 return node.cnt; 54 } 55 for(int i=0;i<4;++i) 56 { 57 if( Judge(node.x+dir[i][0],node.y+dir[i][1]) ) 58 { 59 MakeNode(node.x+dir[i][0],node.y+dir[i][1],node.cnt+1,tempNode); 60 Q.push (tempNode); 61 } 62 } 63 } 64 } 65 66 int main() 67 { 68 int nCases; 69 scanf("%d",&nCases); 70 while( nCases-- ) 71 { 72 int sX,sY,eX,eY; 73 scanf("%d%d%d%d",&sX,&sY,&eX,&eY); 74 memcpy(mazeH,maze,sizeof(maze));//把maze拷贝到mazeH中; 75 int ans=bfs(sX,sY,eX,eY);//bfs搜索 76 printf("%d\n",ans); 77 } 78 return 0; 79 }