bfs宽搜
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#define fi first
#define se second
using namespace std;
const int N = 401;
typedef pair<int,int> PII;
queue <PII> q;
int f[N][N];
int n,m,x1,y1;
int d[][2] = {{2,1} , {1,2} , {-2 , -1} , {-1 , -2} , {-2 , 1} , {2 , -1} , {1,-2} , {-1 ,2}};
void bfs()
{
q.push({x1,y1});
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0 ; i < 8 ; i++)
{
int x = t.fi + d[i][0];
int y = t.se + d[i][1];
if(x <= n && y <= m && x >= 1 && y >= 1 && f[x][y] == -1)
{
f[x][y] = f[t.fi][t.se] + 1;
q.push({x,y});
}
}
}
}
int main()
{
cin>>n>>m>>x1>>y1;
memset(f,-1,sizeof f);
f[x1][y1] = 0;
bfs();
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= m ; j++)
{
if(f[i][j] < 0) printf("%d ",f[i][j]);
else printf("%d ",f[i][j]);
}
cout<<endl;
}
return 0;
}