题解
2026-08-17 21:35:05
发布于:湖南
2阅读
0回复
0点赞
题意
行 列棋盘,马给定起点坐标,马走日( 个方向)。用 BFS 求起点到棋盘每一格最少步数;无法到达输出 -1。输出矩阵每个数字左对齐,占 格宽度。
思路
BFS(广度优先搜索),BFS 天然求最短路,适合无权图最少步数;
马一共 个移动方向;
vis 数组标记是否入队,防止重复进队列;ans 数组存最少步数,初始全部填 ‑1;
起点步数 ,入队;每次出队,向 方向拓展,合法且未访问的点入队,步数 +1;
输出使用 setw(5) 左对齐,每个输出占 字符宽度。
完整代码
#include <bits/stdc++.h>
using namespace std;
struct P {
int x,y,st;
};
int n,m;
int sx,sy;
int d[][2] = {{2, 1}, {1, 2}, {-2, 1}, {-1, 2}, {-1, -2}, {1, -2}, {-2, -1}, {2, -1}};
int vis[405][405];
int ans[405][405];
void bfs() {
queue<P> q;
q.push({sx,sy,0});
vis[sx][sy] = 1;
while (!q.empty()) {
P now = q.front();
q.pop();
ans[now.x][now.y] = now.st;
for (int i = 0; i < 8; i++) {
int nx = now.x + d[i][0];
int ny = now.y + d[i][1];
if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
if (vis[nx][ny] == 1) continue;
q.push({nx,ny,now.st+1});
vis[nx][ny] = 1;
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
memset(ans,-1,sizeof ans);
cin >> n >> m >> sx >> sy;
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cout << left << setw(5) << ans[i][j];
}
cout << '\n';
}
return 0;
}

这里空空如也








有帮助,赞一个