ACWING 844. 走迷宫
阅读原文时间:2023年07月10日阅读:1

地址 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),表示完整的二维数组迷宫。

输出格式

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

数据范围

1≤n,m≤100

输入样例:

输出样例:

解法

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

#include
#include
#include

using namespace std;

const int N = ;

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

int n, m;

typedef pair PII;

queue que;

int rowadd[] = { ,-,, };
int coladd[] = { ,,,- };

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

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

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

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

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

}

}

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

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

return ;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章