#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct Node{
int x, y, step; // 位置 和 步数
};
int n,m;
int vis[505][505];
int dx[8] = {-2,-2,-1, 1, 2, 2, 1,-1};
int dy[8] = {-1, 1, 2, 2, 1,-1,-2,-2};
void bfs(int sx, int sy){
// -1初始化每个点都走不到
memset(vis, -1, sizeof(vis));
queue<Node> q;
q.push({sx,sy,0});
vis[sx][sy] = 0;
while(!q.empty()){
Node t = q.front();
q.pop();
for(int i=0;i<8;i++){
int xx = t.x + dx[i];
int yy = t.y + dy[i];
// 不能走出棋盘 走过的不能走
if(xx>=1 && xx<=n && yy>=1 && yy<=m && vis[xx][yy]==-1){
q.push({xx, yy, t.step +1 });
vis[xx][yy] = t.step + 1;
}
}
}
}
int main(){
int x,y;
cin>>n>>m>>x>>y;
bfs(x,y);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
printf("%-5d", vis[i][j]);
}
cout<<endl;
}
return 0;
}
上学之路5
int dx[12] = {-2,-1,1,2,2,1,-1,-2,-2,2,-2,2};
int dy[12] = {1,2,2,1,-1,-2,-2,-1,2,2,-2,-2};