洛谷 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

相关推荐
做时间的朋友。1 小时前
精准核酸检测
java·数据结构·算法
如君愿2 小时前
考研复习 Day28 | 习题--计算机网络第四章(网络层 中)、数据结构(树与二叉树 下)
数据结构·计算机网络·考研·课后习题·记录考研
江南十四行2 小时前
排序算法进阶:直接插入排序(简单排序)与希尔排序
数据结构·算法·排序算法
洛水水2 小时前
【Redis入门】一篇详解Redis五大数据结构
数据结构·数据库·redis
CoderCodingNo2 小时前
【CSP】CSP-J 2021真题 | 插入排序 luogu-P7910 (适合GESP四-六级及以上考生练习)
数据结构·算法·排序算法
努力努力再努力wz3 小时前
【MySQL进阶系列】一文打通事务机制:从锁、Undo Log 到 MVCC 与隔离级别
c语言·数据结构·数据库·c++·mysql·算法·github
薇茗3 小时前
【初阶数据结构】 左右逢源的分支诗律 二叉树1
c语言·数据结构·算法
澈2073 小时前
C++ string全面解析:从入门到精通
数据结构·c++·算法
Irissgwe4 小时前
算法之滑动窗口
数据结构·算法