bfs + pair
用bfs跑一遍,并用pair记录一下每个点的前驱
最后倒着遍历一下每个点的前驱,存入vector中,倒着输出即可。
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n;
int d[N][N];
int g[N][N];
PII res[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void bfs()
{
queue<PII> q;
q.push({0, 0});
d[0][0] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i ++ )
{
int x = t.x + dx[i], y = t.y + dy[i];
if (x >= 0 && x < n && y >= 0 && y < n && d[x][y] == -1 && g[x][y] != 1)
{
d[x][y] = d[t.x][t.y] + 1;
res[x][y] = {t.x, t.y};
q.push({x, y});
}
}
}
vector<PII> ans;
int len = d[n - 1][n - 1];
int a = n - 1, b = n - 1;
while (len -- )
{
ans.push_back({res[a][b].x, res[a][b].y});
int t = res[a][b].x;
b = res[a][b].y, a = t;
}
for (int i = ans.size() - 1; i >= 0; i -- )
{
cout << ans[i].x << ' ' << ans[i].y << endl;
}
cout << n - 1 << ' ' << n - 1 << endl;
}
int main()
{
cin >> n;
memset(d, -1, sizeof d);
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++)
cin >> g[i][j];
bfs();
return 0;
}