描述
这有一个迷宫,有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<cstring> #include<queue> using namespace std; typedef pair<int,int> P; int a[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 b[9][9],T,x1,y1,x2,y2; int c1[] = {-1,1,0,0}; int c2[] = {0,0,-1,1}; queue<P> que; int main(){ cin>>T; while(T--){ for(int i = 0;i < 9;i++) for(int j = 0;j < 9;j++) b[i][j] = 65535; cin>>x1>>y1>>x2>>y2; b[x1][y1] = 0; que.push(P(x1,y1)); while(!que.empty()){ P temp = que.front();que.pop(); //判断是否到达终点 if(temp.first == x2 && temp.second == y2) break; for(int i = 0;i < 4;i++){ int x = temp.first + c1[i],y = temp.second + c2[i]; if(x >= 0 && x < 9 && y >= 0 && y < 9 && a[x][y] == 0 && b[x][y] == 65535){ que.push(P(x,y)); b[x][y] = b[temp.first][temp.second] + 1; } } } while(!que.empty()) que.pop(); cout<<b[x2][y2]<<endl; } return 0; }