54 lines
1.4 KiB
C++
54 lines
1.4 KiB
C++
#include <bits/stdc++.h>
|
||
|
||
using namespace std;
|
||
|
||
int n, m; //n*m的棋盘
|
||
int x, y; //马的位置
|
||
const int N = 410;
|
||
int ans[N][N]; //到任意点需要最少走几步
|
||
//坐标
|
||
struct coord {
|
||
int x, y;
|
||
};
|
||
queue<coord> q;
|
||
//马的八大方向坐标位移
|
||
int walk[8][2] = {{2, 1},
|
||
{1, 2},
|
||
{-1, 2},
|
||
{-2, 1},
|
||
{-2, -1},
|
||
{-1, -2},
|
||
{1, -2},
|
||
{2, -1}};
|
||
|
||
int main() {
|
||
//输入棋盘大小和马的位置
|
||
cin >> n >> m >> x >> y;
|
||
|
||
//标识为-1,表示没有探索过
|
||
memset(ans, -1, sizeof ans);
|
||
|
||
//马入队列
|
||
q.push({x, y});
|
||
ans[x][y] = 0;//出发点标识为最少走0步
|
||
|
||
while (!q.empty()) {
|
||
coord u = q.front();
|
||
q.pop();
|
||
for (int k = 0; k < 8; k++) {//8个方向
|
||
int x = u.x + walk[k][0], y = u.y + walk[k][1];//可能达到的下一步坐标
|
||
if (x < 1 || x > n || y < 1 || y > m || ans[x][y] != -1)continue;
|
||
//步数等于上一级来的位置+1
|
||
ans[x][y] = ans[u.x][u.y] + 1;
|
||
//入队列
|
||
q.push({x, y});
|
||
}
|
||
}
|
||
//输出结果
|
||
for (int i = 1; i <= n; i++) {
|
||
for (int j = 1; j <= m; j++)
|
||
printf("%-5d", ans[i][j]); //左对齐
|
||
puts("");
|
||
}
|
||
return 0;
|
||
} |