用node pre[x][y]记录pre[x][y]的上一个节点从而用一个递归倒序打印结果。
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int m[10][10];
int vis[10][10];
struct node {
int x;
int y;
};
node pre[100][100]; // 记忆父节点
int dx[] = {0 , 1, 0, -1};
int dy[] = {1, 0, -1, 0};
void print_ans(int x, int y) {
if (x == 0 && y == 0) {
return;
}
print_ans(pre[x][y].x, pre[x][y].y);
printf("(%d, %d)\n", x, y);
}
void bfs()
{
queue<node> qu;
node temp;
temp.x = 0;
temp.y = 0;
qu.push(temp);
memset(vis, 0, sizeof(vis));
vis[0][0] = 1;
while(!qu.empty()) {
node t = qu.front(); qu.pop();
if (t.x == 4 && t.y == 4) {
break;
}
for(int i = 0; i < 4; i++) {
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if (vis[nx][ny] || nx >= 5 || ny >= 5 || nx < 0 || ny < 0 || m[nx][ny]) {
continue;
}
vis[nx][ny] = 1;
node v;
v.x = nx;
v.y = ny;
qu.push(v);
pre[nx][ny] = t;
}
}
printf("(0, 0)\n");
print_ans(4, 4);
}
int main() {
//freopen("input.txt", "r", stdin);
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
scanf("%d", &m[i][j]);
}
}
bfs();
return 0;
}