洛谷 P1443:马的遍历 ← BFS

【题目来源】
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

相关推荐
个 人 练 习 生6 分钟前
数据结构链表:带头双向循环链表
c语言·数据结构·经验分享·学习·其他·链表
我变成萤火虫6 小时前
河南萌新联赛2026第(四)场:南阳理工学院
数据结构·c++·算法·贪心算法·stl·动态规划
疯狂打码的少年15 小时前
【数据结构】图的遍历:深度优先搜索(DFS)
数据结构·笔记·算法·深度优先
土司大王18 小时前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
神威难绷泪1 天前
数据结构:哈希表 算法相关 排序算法
数据结构
Zguigo1 天前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
2401_869769591 天前
list 2
数据结构·list
ambition202421 天前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
疯狂打码的少年2 天前
【数据结构】图的存储结构:邻接矩阵与邻接表
数据结构·笔记
203号居民2 天前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode