描述
这有一个迷宫,有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 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[4][2]={-1,0,1,0,0,-1,0,1};
int vis[9][9]={0};
typedef struct node
{
int x,y;//记录坐标
int step;//记录步数
}No;
queue<node>Q;
int bfs(int x1, int y1, int x2, int y2)
{
int i,s,t;
No e={x1,y1,0};//开始时,步数为零时的坐标
Q.push(e);//将可以走的方格插入到队列
vis[x1][y1]=1;//已被走过
while(!Q.empty())//当队列不为空时
{
e=Q.front();//e为队列的第一个元素
if(e.x == x2 && e.y == y2) //到达终点
{
break;
}
Q.pop();//取出队列的第一个元素
for(i=0;i<4;i++)
{
s=e.x+b[i][0];
t=e.y+b[i][1];
if(s>=0 && s<=8 && t >= 0 && t <= 8 && !vis[s][t] && a[s][t] ==0)//未被访问过,并且为通路
{
No e1={s,t,e.step+1};//步数加一
Q.push (e1);//将e1插入队列
vis[s][t]=1;//已被访问
}
}
}
if(Q.empty())//队列为空
{
return -1;
}
while(!Q.empty())//队列不为空
{
Q.pop();//清空队列
}
return e.step;
}
int main()
{
int k,x1,x2,y1,y2;
int n;
scanf("%d", &n);
while(n--)
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
memset(vis,0,sizeof(vis));
k=bfs(x1,y1,x2,y2);///广度搜索
printf("%d\n",k);
}
return 0;
}