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

相关推荐
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠2 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
Qres8212 天前
算法复键——树状数组
数据结构·算法
牛油果子哥q2 天前
并查集(DSU)超精讲,路径压缩、按秩合并、万能模板、连通性判定、最小生成树与刷题实战全解
数据结构·c++·最小生成树·并查集
凌波粒2 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
WL学习笔记2 天前
单项不带头不循环链表
数据结构·链表
小糯米6012 天前
JS 数组
数据结构·算法·排序算法
小欣加油2 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒2 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode