题面
题解(最短路模型)
迷宫问题+输出路径,因为每个点之间的距离都是1,所以用BFS搜索出来的结果就是最短的距离,我们新开一个数组,然后我们从终点开始最终搜索到起点,记录每个点的前一个点是从哪转移过来的,最后从(0,0)点遍历一遍即可
代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n;
int g[N][N];
PII q[N * N];
PII pre[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};
void bfs(int sx, int sy) {
memset(pre, -1, sizeof pre);
pre[sx][sy] = {0, 0};
int hh = 0, tt = -1;
q[++tt] = {sx, sy};
while (hh <= tt) {
PII t = q[hh++];
int x = t.first, y = t.second;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1) continue;
if (pre[nx][ny].first != -1) continue; //说明已经遍历过
if (g[i][j]) continue;
q[++tt] = {nx, ny};
pre[nx][ny] = t; //从后往前遍历,记录上一个点
}
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> g[i][j];
}
}
bfs(n - 1, n - 1);
PII end = {0, 0}; //正向输出
while (true) {
cout << end.first << " " << end.second << endl;
if (end.first == n - 1 && end.second == n - 1) break;
end = pre[end.first][end.second];
}
return 0;
}