算法1
C++ 代码
//https://www.luogu.com.cn/record/145360360
//马的遍历 简单bfs
#include <bits/stdc++.h>
using namespace std;
const int N = 410;
int mp[N][N], sol[N][N], n, m, x, y;
bool vis[N][N];
int d[][2] = {1,2,1,-2,-1,2,-1,-2,-2,1,-2,-1,2,1,2,-1};//八个方向
typedef pair<int,int> pii;
bool inmap(int x, int y){
return (x >= 1 && x <= n && y >= 1 && y <= m);
}
void bfs(){
//int catch = 0;
queue<pii> q; q.push({x,y}); vis[x][y] = true;
sol[x][y] = 0;
while(!q.empty()){
auto pp = q.front(); q.pop();
for(int i = 0; i < 8; ++ i){
int xx = pp.first + d[i][0], yy = pp.second + d[i][1];
if(inmap(xx,yy) && !vis[xx][yy]){
vis[xx][yy] = true;
sol[xx][yy] = sol[pp.first][pp.second] + 1;
q.push({xx,yy});
}
}
}
}
int main()
{
cin >> n >> m >> x >> y;
bfs();
for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= m; ++ j){
if(!vis[i][j]) cout << "-1 ";
else cout << sol[i][j] << ' ';
}
cout << '\n';
}
return 0;
}