反向bfs并记录路径中每个点的前驱,从bfs终点访问每个点的前驱就是答案
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, len;
int g[N][N];
int d[N][N];
pair<int, int> pre[N][N];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, -0, -1};
void bfs () {
memset(d, -1, sizeof d);
queue<pair<int, int>> q;
d[n-1][n-1] = 0;
q.push({n-1, n-1});
while (q.size()) {
pair<int, int> p = q.front();
q.pop();
int px = p.first, py = p.second;
for (int i = 0; i < 4; i++) {
int x = px + dx[i], y = py + dy[i];
if (x >= 0 && y >= 0 && x < n && y < n && g[x][y] == 0 && d[x][y] == -1) {
d[x][y] = d[px][py] + 1;
q.push({x, y});
pre[x][y] = {px, py};
}
}
}
len = d[0][0];
}
int main(){
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> g[i][j];
}
}
bfs();
int x = 0, y = 0;
cout << x << ' ' << y << '\n';
for (int i = 0; i < len; i++) {
pair<int, int> p = pre[x][y];
x = p.first, y = p.second;
cout << x << ' ' << y << '\n';
}
return 0;
}