[C++][算法基础]走迷宫(BFS)

给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。

最初,有一个人位于左上角 (1,1)(1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角 (n,m)处,至少需要移动多少次。

数据保证 (1,1)(1,1) 处和 (n,m) 处的数字为 00,且一定至少存在一条通路。

输入格式

第一行包含两个整数 n 和 m。

接下来 n 行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。

输出格式

输出一个整数,表示从左上角移动至右下角的最少移动次数。

数据范围

1≤n,m≤100

输入样例:
复制代码
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<queue>
using namespace std;

const int N = 110;

int n,m;
int G[N][N];
int dist[N][N];
queue<pair<int,int>> Q;

int bfs(){
    int head = 0,tail = 0;
    int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
    dist[0][0] = 0;
    Q.push({0,0});
    while(Q.size()!=0){
        auto now = Q.front();
        Q.pop();
        for(int i = 0;i < 4;i++){
            int x = now.first + dx[i];
            int y = now.second + dy[i];
            if(x >= 0 && x < n && y >= 0 && y < m && G[x][y] == 0 &&dist[x][y] == -1){
                dist[x][y] = dist[now.first][now.second] + 1;
                Q.push({x,y});
            }
        }
    }
    return dist[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];
            dist[i][j] = -1;
        }
    }
    cout<<bfs();
    return 0;
}
相关推荐
小白菜又菜3 分钟前
Leetcode 1523. Count Odd Numbers in an Interval Range
算法·leetcode
你们补药再卷啦31 分钟前
人工智能算法概览
人工智能·算法
cnxy18836 分钟前
围棋对弈Python程序开发完整指南:步骤3 - 气(Liberties)的计算算法设计
python·算法·深度优先
AndrewHZ1 小时前
【图像处理基石】什么是光栅化?
图像处理·人工智能·算法·计算机视觉·3d·图形渲染·光栅化
小白菜又菜1 小时前
Leetcode 944. Delete Columns to Make Sorted
算法·leetcode
博语小屋1 小时前
转义字符.
c语言·c++
Lhan.zzZ1 小时前
Qt跨线程网络通信:QSocketNotifier警告及解决
开发语言·c++·qt
Aevget1 小时前
QtitanDocking 如何重塑制造业桌面应用?多视图协同与专业界面布局实践
c++·qt·界面控件·ui开发·qtitandocking
我找到地球的支点啦1 小时前
Matlab系列(006) 一利用matlab保存txt文件和读取txt文件
开发语言·算法·matlab
-森屿安年-1 小时前
STL中 Map 和 Set 的模拟实现
开发语言·c++