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

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

题目描述

输入样例

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;
}
相关推荐
Fuliy965 分钟前
数学建模--智能算法之鱼群算法
python·算法·数学建模·智能算法·鱼群算法·数学建模智能算法
T0uken11 分钟前
【算法模板】图论:Tarjan算法求割边割点
算法·图论
broad-sky27 分钟前
人脸识别Arcface的Tensorrt C++
图像处理·pytorch·深度学习·opencv·算法·计算机视觉·边缘计算
数懒女士36 分钟前
Java中等题-括号生成(力扣)
java·算法·leetcode
sjtu_cjs1 小时前
贪心算法part04
算法·贪心算法
羊毛_1 小时前
131. 分割回文串
算法·深度优先
fhvyxyci1 小时前
C语言自定义类型联合体与枚举超详解
c语言·开发语言·c++·算法·visual studio
A22742 小时前
LeetCode 66, 169, 215
java·算法·leetcode
吱吱喔喔2 小时前
请编程实现一个冒泡排序算法?
数据结构·算法
凭君语未可2 小时前
数据结构:线性表顺序存储结构
数据结构·算法