思路:BFS具有最短的性质那么,只需要考虑如何打印最短路,我们用个pair的二维数组存储到达当前位置的前一步是哪一步,为了方便输出,我们从n,n点出发到1,1,点
#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>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e5+10;
const int inf=0x3f3f3f3f;
const int maxx=2e5+7;
const double eps=1e-6;
int gcd(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 <class T>
void read(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 <class T>
void write(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;
void bfs()
{
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});
}
}
}
int main()
{
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];
}
return 0;
}