以下为代码
#include <iostream>
#include <cstring>
using namespace std;
struct pos{
int x,y,step;
};
pos q[160000];int res[410][410] = {-1};int visit[410][410] = {0};
int x[] = {1,1,-1,-1,2,2,-2,-2},y[] = {2,-2,2,-2,1,-1,1,-1};
int n,m,c,d;
int main(){
memset(res,-1,sizeof res);
cin >> n >> m >> c >> d;
int head = 0;int tail = 0;
q[head].x = c - 1,q[head].y = d - 1,q[head].step= 0,visit[c-1][d-1] = 1;
tail ++;
while (head != tail){
for (int i = 0;i < 8;i++){
int e = q[head].x + x[i],f = q[head].y + y[i];
if ((visit[e][f]) || (e < 0 ||e > n || f < 0 || f > m )) continue;
else visit[e][f] = 1;
q[tail++] = {e,f,q[head].step+1};
}
res[q[head].x][q[head].y] = q[head].step;
head++;
}
for (int i = 0;i < n;i++){
for (int j = 0;j < m;j++){
cout << res[i][j]<< "\t";
}
cout << endl;
}
return 0;
}