参考网址
https://blog.csdn.net/wr132/article/details/45419507
解题思路:
问题的关键在于记录路径
本题目中,使用string类型的字符串来记录路径。
由于解唯一,故而一旦到达终点,那么就一定是唯一的最短路径
也就是说,不存在两个点p和q,它们能够在下一次经过同一个点r
所以我们直接bfs,每一轮将经过的点加入t即可
当bfs到(4, 4)的时候输出string,也就是记录的路径
C++代码如下:
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
const int maxn = 5;
int a[maxn][maxn]; // 用于存储迷宫
int vis[maxn][maxn]; // 用于标记该点是否被走过
int dx[] = {0, 0, -1, 1}; // x轴的移动方位,与y轴方位dy对齐使用(dx[i], dy[i])
int dy[] = {1, -1, 0, 0}; // y轴的移动方位
struct point
{
int x; // 记录点的横坐标
int y; // 记录点的纵坐标
string path; // 用于记录路径
point(int x_, int y_, string path_) // 构造函数
{
x = x_;
y = y_;
path = path_;
}
point(){}
};
string bfs() // a[0][0] => a[4][4]
{
queue<point> q; // 用q来表示迷宫中的点及其经过的路径
string t = "(0, 0)\n"; // 初始化路径t
q.push(point(0, 0, t)); // 初始化队列
vis[0][0] = 1; // 第一个点默认为被走过
while(!q.empty()) // 当队列不为空,即可以继续bfs,也就是还能够在走下去的时候
{
// 上下左右
point p = q.front(); // 取出第一个顶点,将其能够到达的所有顶点标记更新
q.pop(); // 弹出顶点(队列先进先出,用完了该顶点,它也就没用了,可以扔掉了)
if (p.x == 4 && p.y == 4) // 到达终点, output
{
return p.path; // 返回路径t,t为字符串
}
for (int i = 0; i < 4; i++)
{
int xx = p.x + dx[i]; // 计算下一个可能到达的点
int yy = p.y + dy[i];
if (xx < 5 && xx >= 0 && yy < 5 && yy >= 0 && a[xx][yy] != 1 && !vis[xx][yy]) // 判断该点是否可行
{ // 可行:1.没有越界(跑出迷宫) 2.该点之前没被经过 3. 该点不是墙
vis[xx][yy] = 1; // 该点合法且已经被bfs经过,则将其vis值置为1
t = p.path; // 用字符串t来记录路径
t += "(";
t += (char)('0' + xx);
t += ", ";
t += (char)('0' + yy);
t += ")\n"; // 换行,以便符合题目的输出要求
q.push(point(xx, yy, t)); // 该点入栈,继续向外圈bfs
}
}
}
}
int main()
{
for (int i = 0; i < 5; i++) // input
{
for (int j = 0; j < 5; j++)
cin >> a[i][j];
}
memset(vis, 0, sizeof(vis)); // initialize
string Path = bfs(); // solve
cout << Path << endl; // output
return 0; // end
}