0.前言
写这道题的时候知道是用bfs(广度优先),基本框架也写了出来,但是不知道怎么保存路径。搜了一下,看了一下别人的,但是实在没看下去。可能是感觉重要地方没有注释,代码耦合性也有点高(也可能没有,反正就是没看下去,我自己问题吧,没沉下心看)
最后只能问gpt,让gpt帮我完善一下,然后就知道了保存前驱结点这一个方法,真的是豁然开朗。(这个方法也不是不知道,但还是练的太少)
1.题目
2.代码
个人感觉自己代码耦合性还是比较低吧,并且也有一定的注释。希望能帮助某些人理解。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct node {
int x, y;
};
int n = 5;
int maze[5][5];
int visited[5][5];
node pre[5][5]; //存储先驱结点
vector<node> path; //存储路径
//表示四个方向
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
//功能:判断该点是否符合题意
//参数:(x,y)为该点的坐标
//返回值:如果该点可以访问,返回true,否则返回false
bool check(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= n) return false;
if (maze[x][y] == 1 || visited[x][y] == true) return false;
return true;
}
void bfs(int x, int y) {
queue<node> q;
q.push({ x,y });
visited[x][y] = true;
while (!q.empty()) {
node t = q.front();
q.pop();
//到达目的点后,保存路径
if (t.x == n - 1 && t.y == n - 1) {
path.push_back({ t.x,t.y });
/*for (int i = t.x, j = t.y; i != x || j != y; i = pre[i][j].x, j = pre[i][j].y) {
path.push_back({ pre[i][j].x,pre[i][j].y });
}在改变i,j的时候出了问题,j在i改变之后改变*/
for (int i = t.x, j = t.y; i != x || j != y; ) {
path.push_back({ pre[i][j].x,pre[i][j].y });
int tempi = i, tempj = j;
i = pre[tempi][tempj].x, j = pre[tempi][tempj].y;
}
return;
}
//向四个方向依次尝试
for (int i = 0; i < 4; ++i) {
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if (check(nx, ny)) {
visited[nx][ny] = true; q.push({ nx,ny });
pre[nx][ny].x = t.x; pre[nx][ny].y= t.y; //保存前驱节点
}
}
}
}
int main() {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> maze[i][j];
bfs(0, 0);
while (!path.empty()) {
cout << "(" << path.back().x << "," << path.back().y << ")" << endl;
path.pop_back();
}
return 0;
}