#include <bits/stdc++.h>
using namespace std ;
const int N = 4e2 + 55 ;
struct node {
int x ;
int y ;
} ;
int ans[N][N] ;
int walk[8][2] = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}} ;
queue<node> q ;
int main() {
int n, m, x, y ;
cin >> n >> m >> x >> y ; // Read once only
memset(ans, -1, sizeof(ans)) ;
node tmp = {x, y} ;
q.push(tmp) ;
ans[x][y] = 0 ;
while (!q.empty()) {
node u = q.front() ;
int ux = u.x ;
int uy = u.y ;
q.pop() ;
for (int k = 0 ; k < 8 ; k++) {
int nx = ux + walk[k][0] ;
int ny = uy + walk[k][1] ;
if (nx < 1 || nx > n || ny < 1 || ny > m || ans[nx][ny] != -1) {
continue ;
}
ans[nx][ny] = ans[ux][uy] + 1 ;
node newPos = {nx, ny} ;
q.push(newPos) ;
}
}
// Print the final result after BFS is complete
for (int i = 1 ; i <= n ; i++) {
for (int j = 1 ; j <= m ; j++) {
printf("%-5d", ans[i][j]) ;
}
cout << endl ;
}
return 0 ;
}1
这是 2026年3月20日 存档的第 1 版,不是当前版本。查看当前版本