ACWING 844. 走迷宫

地址 https://www.acwing.com/problem/content/description/846/

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

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

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

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

输入格式

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

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

输出格式

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

数据范围

1n,m100

输入样例:
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

解法  

BFS搜索  不采取DFS是因为BFS可以获取最短路径

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 110;

int g[N][N];
int dis[N][N];

int n, m;

typedef pair<int, int> PII;

queue<PII> que;

int rowadd[4] = { 1,-1,0,0 };
int coladd[4] = { 0,0,1,-1 };

void bfs(int row, int col)
{
    while (!que.empty())
    {
        PII xy = que.front();
        que.pop();

        for (int i = 0; i < 4; i++) {
            int nextrow = xy.first + rowadd[i];
            int nextcol = xy.second + coladd[i];

            if (nextrow == n && nextcol == m) {
                //达到终点
                cout << (dis[xy.first][xy.second] + 1) << endl;
                return;
            }

            if (nextrow >= 1 && nextrow <= n && nextcol >= 1 && nextcol <= m)
            {
                if (g[nextrow][nextcol] == 0) {
                    g[nextrow][nextcol] = 1;

                    dis[nextrow][nextcol] = dis[xy.first][xy.second] + 1;
                    que.push({ nextrow,nextcol });
                }
            }
        }


    }

}



int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> g[i][j];
        }
    }



    que.push({ 1,1 });
    g[1][1] = 1;
    dis[1][1] = 0;
    bfs(1, 1);


    return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/11630340.html