搜索与图论:宽度优先搜索

搜索与图论:宽度优先搜索

题目描述

输入样例

复制代码
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

输出样例

复制代码
8

参考代码

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int N = 110;

typedef pair<int, int> PII;

int n, m;
int g[N][N];    // 存储地图
int d[N][N];    // 每一个点到起点的距离
PII q[N * N], Prev[N][N];

int bfs()
{
    int hh = 0, tt = 0;
    q[0] = {0, 0};
    
    memset(d, -1, sizeof d);
    d[0][0] = 0;
    
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    
    while (hh <= tt)
    {
        auto t = q[hh ++];
        
        for (int i = 0; i < 4; i++)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
            {
                d[x][y] = d[t.first][t.second] + 1;
                Prev[x][y] = t;
                q[++ tt] = {x, y};
            }
        }
    }
    
    int x= n - 1, y = m - 1;
    while (x || y)
    {
        cout << x << ' ' << y << endl;
        auto t = Prev[x][y];
        x = t.first, y = t.second;
    }
    return d[n - 1][m - 1];
}

int main()
{
    cin >> n >> m;
    
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> g[i][j];
            
    cout << bfs() << endl;
    
    return 0;
}
相关推荐
Swift社区1 天前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555551 天前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
让我们一起加油好吗1 天前
【基础算法】DFS中的剪枝与优化
算法·深度优先·剪枝
Q741_1471 天前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
Felven1 天前
A. Be Positive
算法
小O的算法实验室1 天前
2026年COR SCI2区,自适应K-means和强化学习RL算法+有效疫苗分配问题,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
青岛少儿编程-王老师1 天前
CCF编程能力等级认证GESP—C++7级—20250927
数据结构·c++·算法
夏鹏今天学习了吗1 天前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
天选之女wow1 天前
【代码随想录算法训练营——Day34】动态规划——416.分割等和子集
算法·leetcode·动态规划
Boop_wu1 天前
[数据结构] 哈希表
算法·哈希算法·散列表