![](https://img-blog.csdnimg.cn/direct/2a0e8370026a467a970abefeb0d2d9f6.png)
![](https://img-blog.csdnimg.cn/direct/411be4d423764551be684173a4a3a783.png)
![](https://img-blog.csdnimg.cn/direct/3a9d4b1031574e3eb56ab5e60bdf4c6b.png)
![](https://img-blog.csdnimg.cn/direct/8738aa41b7d44758890475d83fccf63d.png)
#include <iostream>
#include <cstring>
#include <queue>
#include <stack>
#define x first
#define y second
using namespace std;
typedef pair<int ,int> PII;
const int N = 1010;
PII pre[N][N];//存储当前位置的前驱
int g[N][N];
bool st[N][N];//表示当前位置的状态,若已用则为true,反之为false.
int n;
int dx[4] = {-1,1,0,0}, dy[4] = {0,0,-1,1};//当前位置的上、下、左、右偏移量
void bfs(){
queue <PII> q;
q.push({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 && g[x][y] == 0 && st[x][y] == false){
st[x][y] = true;
pre[x][y] = t;//存储一下当前合理位置的前驱,即该位置由哪个位置引入
q.push({x, y});
}
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i ++){
for(int j = 0; j < n; j ++){
cin >> g[i][j];
}
}
bfs();
stack<PII> s;
int x = n - 1, y = n - 1;
while(x || y){
s.push({x, y});
auto t = pre[x][y];
x = t.x, y = t.y;
}
s.push({0, 0});
//打印方案
while(s.size()){
PII t = s.top(); s.pop();
cout << t.x << ' ' << t.y << endl;
}
return 0;
}