题目传送门
简单bfs遍历 用pre记录前驱路径
#include <bits/stdc++.h>
#define pii pair<int,int>
#define x first
#define y second
using namespace std;
const int N = 1010;
int g[N][N];
bool st[N][N];
pii pre[N][N]; // 前驱数组
queue<pii> q;
int n = 5, m = 5;
int dy[] = {-1,1,0,0}, dx[] = {0,0,1,-1};
void bfs(){
q.push({0,0});
st[0][0] = true;
pre[0][0] = {-1,-1};
while(q.size()){
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i ++){
int tx = dx[i] + t.x, ty = dy[i] + t.y;
if(st[tx][ty] || tx < 0 || tx >= n || ty < 0 || ty >= m || g[tx][ty] == 1) continue;
st[tx][ty] = true;
pre[tx][ty] = {t.x,t.y};
q.push({tx,ty});
}
}
}
int main()
{
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j ++)
cin >> g[i][j];
}
bfs();
pii ans = {n-1,m-1};
vector<pii> res;
while(ans.x != -1){
res.push_back({ans.x,ans.y});
ans = pre[ans.x][ans.y];
}
for(int i = res.size() -1 ; i >= 0; i --){
printf("(%d, %d)\n",res[i].x,res[i].y);
}
}