https://www.luogu.com.cn/problem/P1443?contestId=67264
AC代码
#include<bits/stdc++.h>
using namespace std;
int dir[8][2]={{2,1},{2,-1},{1,2},{1,-2},{-2,1},{-2,-1},{-1,2},{-1,-2}};
struct node
{
int x,y;
}now;
int g[410][410],bk[410][410];
int n,m,x,y;
void bfs(int x,int y,int step)
{
now.x=x,now.y=y;
bk[x][y]=1;
queue<node> q;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<8;i++)
{
int tx=now.x+dir[i][0];
int ty=now.y+dir[i][1];
if(bk[tx][ty]==0&&tx>=1&&tx<=n&&ty>=1&&ty<=m)
{
bk[tx][ty]=1;
q.push({tx,ty});
g[tx][ty]=g[now.x][now.y]+1;
}
}
}
}
int main()
{
cin>>n>>m>>x>>y;
memset(g,-1,sizeof g);
g[x][y]=0;
bfs(x,y,0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%-5d",g[i][j]);
printf("\n");
}
return 0;
}