题目描述
现在有一个5*5的迷宫,起点在左上角,终点在右下角,现在请你来写一个程序计算一下,LZY从起点开始走迷宫,最终能否成功的逃离迷宫?
如果LZY可以逃出迷宫,请输出逃离迷宫的最短路径,否则输出 “No path”
输入
测试样例由多组测试数据组成,每组测试数据输入一个5 * 5的矩阵,矩阵中只包含 0 和 1
0 代表可以走的路径
1 代表障碍物,不能通行
输出
如果LZY能够逃离迷宫,则输出逃离迷宫的最短路径 (格式参考样例)
否则输出 “No path”
如果有多条最短路径,你只需要输出任意一条即可
样例输入 Copy
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
样例输出 Copy
path: 1 —> (0, 0)
path: 2 —> (1, 0)
path: 3 —> (2, 0)
path: 4 —> (2, 1)
path: 5 —> (2, 2)
path: 6 —> (2, 3)
path: 7 —> (2, 4)
path: 8 —> (3, 4)
path: 9 —> (4, 4)
- 题意,这题求最短路径,难在如何保存路径
- 只要用一个数组,每个数组的的值就是上一次的位置
#include<bits/stdc++.h>
using namespace std;
int a[5][5];
int dir[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};
struct q1{
int x, y;
}cur, xia, ba[5][5];
int bfs(){
queue<q1> q;
cur.x = 0, cur.y = 0;
q.push(cur);
a[0][0] = 1;
while(!q.empty()){
int x = q.front().x;
int y = q.front().y;
if(x == 4 && y == 4)return 1;
q.pop();
for(int i = 0; i < 4; i ++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 0 || ty < 0 || tx > 4 || ty > 4)continue;
if(a[tx][ty] == 1)continue;
a[tx][ty] = 1;
xia.x = tx;
xia.y = ty;
q.push(xia);
ba[tx][ty].x = x;
ba[tx][ty].y = y;
}
}
return 0;
}
int main(){
ios::sync_with_stdio(false);
while(cin >> a[0][0]){
// memset(vis,0,sizeof(vis));
memset(ba,0,sizeof(ba));
for(int i = 0; i < 5; i ++)
for(int j = 0; j < 5; j ++){
if(i == 0 && j == 0)continue;
cin>> a[i][j];
}
if(a[0][0] == 1){
cout << "No path" << endl;
continue;
}
int temp = bfs();
int s[10][2],cnt = 0;
if(temp){
int x = 4, y = 4;
while(1){
int tx = x, ty = y;//一定要用tx,ty,不然会重复
cnt ++ ;
s[cnt][0] = x;
s[cnt][1] = y;
x = ba[tx][ty].x;
y = ba[tx][ty].y;
if(x == 0 && y == 0)break;
}
//这下面实在太乱,只要知道是输出就可以了
int aka = 1;
cout << "path: " << aka << " ---> (" << 0 << ", " << 0 << ")" << endl;
for(int i = cnt; i >= 1; i --){
aka ++;
cout << "path: " << aka << " ---> (" << s[i][0] << ", " << s[i][1] << ")" << endl;
}
}else {
cout << "No path" << endl;
}
}
return 0;
}