走迷宫求最短路径问题
有一个迷宫,有08行和08列:
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)。数据保证起点一定能够到达
Input:
第一行输入一个整数n(0<n<=100),表示有n组测试数据; 随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
Output:
输出最少走几步。
Sample Input:
2
3 1 5 7
3 1 6 7
Sample Output:
12
11
#include <iostream>
#include <queue>
using namespace std;
int maze[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 d[4][2]={{0,1},{0,-1},{-1,0},{1,0}}; //方向数组,上下左右四个方向
int ds[9][9]; //存储距离出发点的距离
typedef pair<int,int> P;
//深搜结束返回的一定是最短距离,因为每次都是向周围走一步,先返回则说明先到终点。
int bfs(int sx,int sy,int gx,int gy){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
ds[i][j]=9999; //一开始将距离出发点的距离统一标记
}
}
queue<P> que;
que.push(P(sx,sy)); //将起点加入队列
ds[sx][sy]=0; //被访问过则标记为0
while(!que.empty()){
P p=que.front(); //出队操作
que.pop();
if(p.first== gx && p.second == gy) break; //如果这时已经到达终点则停止搜索
for(int i=0;i<4;i++){
int nx=p.first+d[i][0];
int ny=p.second+d[i][1];
if(nx>=0 && nx<9 && ny>=0 && ny<9 && maze[nx][ny]!=1 && ds[nx][ny]==9999){ //在范围内而且不是墙并且没有被访问过则加入队列
que.push(P(nx,ny)); //符合条件入队
ds[nx][ny]=ds[p.first][p.second]+1; //在上个点的基础上距离加一,因为走了一步。
}
}
}
return ds[gx][gy]; //返回最短距离
}
main(){
int n;
cin>>n;
while(n--){
int a,b,c,d;
cin>>a>>b>>c>>d;
cout<<bfs(a,b,c,d)<<endl;
}
}