Idea: BFS has the shortest nature. So, we only need to consider how to print the shortest path. We use a pair of two-dimensional array to store which step is the previous step to the current position. To facilitate the output, we start from n, n to 1, 1 o'clock
#pragma GCC optimize(2)#include<cstdio>#include<cstring>#include<algorithm>#include<set>#include<iostream>#include<vector>#include<queue>#include<map>#include<stack>#include<iomanip>#include<cstring>#include<time.h>usingnamespace std;typedeflonglong ll;#define SIS std::ios::sync_with_stdio(false)#define space putchar(' ')#define enter putchar('\n')#define lson root<<1#define rson root<<1|1typedef pair<int,int> PII;constint mod=1e9+7;constint N=2e6+10;constint M=1e5+10;constint inf=0x3f3f3f3f;constint maxx=2e5+7;constdouble eps=1e-6;intgcd(int a,int b){
return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b){
return a*(b/gcd(a,b));}template<classT>voidread(T &x){
char c;bool op =0;while(c =getchar(), c <'0'|| c >'9')if(c =='-')
op =1;
x = c -'0';while(c =getchar(), c >='0'&& c <='9')
x = x *10+ c -'0';if(op)
x =-x;}template<classT>voidwrite(T x){
if(x <0)
x =-x,putchar('-');if(x >=10)write(x /10);putchar('0'+ x %10);}
ll qsm(int a,int b,int p){
ll res=1%p;while(b){
if(b&1)
res=res*a%p;
a=1ll*a*a%p;
b>>=1;}return res;}int n, m,k;int dir[8][2]={
{
1,0},{
0,1},{
0,-1},{
-1,0}};int mp[1005][1005];int vis[1005][1005];
queue<PII> q;
PII pre[1005][1005];int cnt=0;voidbfs(){
vis[n][n]=1;memset(pre,-1,sizeof pre);
q.push({
n,n});while(!q.empty()){
PII now=q.front();q.pop();if(now.first==1&&now.second==1){
break;}for(int i=0;i<4;i++){
int xx=now.first+dir[i][0];int yy=now.second+dir[i][1];if(xx<1||xx>n||yy<1||yy>n)continue;if(pre[xx][yy].first!=-1||mp[xx][yy])continue;
pre[xx][yy]=now;
q.push({
xx,yy});}}}intmain(){
//int n,m;int ans=0;scanf("%d",&n);for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)scanf("%d",&mp[i][j]);bfs();
PII path({
1,1});while(1){
printf("%d %d\n",path.first-1,path.second-1);if(path.first==n&&path.second==n)break;
path=pre[path.first][path.second];}return0;}