【题目来源】
https://www.luogu.com.cn/problem/P1443
【题目描述】
有一个 n×m 的棋盘,在某个点 (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
【输入格式】
输入只有一行四个整数,分别为 n,m,x,y。
【输出格式】
一个 n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 −1)。
【输入样例】
3 3 1 1
【输出样例】
0 3 2
3 -1 1
2 1 4
【数据范围】
对于全部的测试点,保证 1≤x≤n≤400,1≤y≤m≤400。
【算法分析】
BFS(广度优先搜索)是一种基于队列(Queue)的图/树遍历算法,其核心逻辑是"由近及远、层层扩散"。它从起点出发,优先访问所有直接相邻的节点(第一层),再逐层向外探索邻居的邻居,以此保证首次到达目标节点时路径一定最短。BFS 是解决无权图最短路径、迷宫寻路及按层遍历等问题的标准算法。
【算法代码】
cpp
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=405;
int dis[N][N];
int dx[]= {-2,-1,1,2,2,1,-1,-2};
int dy[]= {1,2,2,1,-1,-2,-2,-1};
int n,m,sx,sy;
void bfs(int sx,int sy) {
memset(dis,-1,sizeof dis);
dis[sx][sy]=0;
queue<PII> q;
q.push({sx,sy});
while(!q.empty()) {
int x=q.front().first;
int y=q.front().second;
q.pop();
for(int i=0; i<8; i++) {
int tx=x+dx[i];
int ty=y+dy[i];
if(tx>=1 && tx<=n && ty>=1 && ty<=m && dis[tx][ty]==-1) {
dis[tx][ty]=dis[x][y]+1;
q.push({tx,ty});
}
}
}
}
int main() {
cin>>n>>m>>sx>>sy;
bfs(sx,sy);
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
cout<<dis[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
/*
in:
3 3 1 1
out:
0 3 2
3 -1 1
2 1 4
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/156341089
https://www.luogu.com.cn/problem/solution/P1443
https://blog.csdn.net/hnjzsyjyj/article/details/158773523
https://www.luogu.com.cn/problem/solution/P1162
https://www.luogu.com.cn/problem/solution/P1135
https://www.luogu.com.cn/problem/solution/P1379
https://www.luogu.com.cn/problem/solution/P1979