题目描述
东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。
Input
输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。
Output
输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。
Example
Sample Input
0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)
Hint
坐标(x, y)表示第x行第y列,行、列的编号从0开始,且以左上角为原点。另外注意,输出中分隔坐标的逗号后面应当有一个空格。
思路
直接BFS求最短路径就好了,记录路径通过新开一个二维数组,记录这个点的前驱点的次序(次序=i*m+j),然后递归输出路径。
总结
查了查网上发现了记录路径的简单方法就是记录到这这个点走的方向,这确实是一个很简洁的方案。
代码
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<queue>
using namespace std;
int map[5][5];
struct site{
int x,y;
};
int size = 0;
queue<site> q;
int fx[4]={0,-1,0,1};
int fy[4]={1,0,-1,0};
void print(int x,int y){
if(x == 0&&y == 0){
cout << "(0, 0)\n";
return;
}
print(map[x][y]/5,map[x][y]%5);
cout <<'(' << x <<", " << y << ")\n";
}
void bfs(int a,int b){
struct site m;
m.x = a; m.y = b;
q.push(m);
map[a][b] = 0;
while(!q.empty()){
int x = q.front().x;
int y = q.front().y;
q.pop();
for(int i = 0; i < 4;i++){
int xx = x + fx[i];
int yy = y + fy[i];
if(map[xx][yy]!=-1||xx<0||xx>4||yy<0||yy>4)
continue;
map[xx][yy] = x*5 + y;
m.x = xx; m.y = yy;
q.push(m);
if(xx == 4 && yy == 4){
print(4,4);
return;
}
}
}
}
int main(){
// freopen("1.txt","r",stdin);
int x;
for(int i = 0; i < 5;i++)
for(int j = 0; j < 5;j++){
cin >> x;
if(x) map[i][j] = -2;
else map[i][j] = -1;
}
bfs(0,0);
return 0;
}