走迷宫【所用算法——bfs】

给定一个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
输入样例:
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,是一个不错的题目
用了两种方式做,一是用数组模拟队列,二是用queue队列来做
第一个题解,用数组模拟队列,在代码中有关于本题的解释

#include <iostream>
#include <cstring>

using namespace std;

typedef pair<int, int> PII;

#define x first
#define y second

const int N = 110;

int n, m;
int g[N][N];
int d[N][N];
PII q[N * N];

int bfs(){
    int hh = 0, tt = 0;//hh为对头,tt为队尾
    q[0] = {0, 0};//将始点放入队列

    memset(d, -1, sizeof d);//两个作用,1:记录是否走过这一点,2:标记当前点到原点的最短距离
    d[0][0] = 0;//一开始就是在始点,所以标记走过,同时离始点距离为0,标记为0

    int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};//偏移量

    while (hh <= tt){//如果栈内还有元素
        auto t = q[hh ++];//让t表示第一个点,同时将第一个点踢出去,因为用过它了,呸,渣男!

        for (int i = 0; i < 4; i ++ ){//让张三走一步
            int x = t.x + dx[i], y = t.y + dy[i];//上下左右都试试
            if (x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1 && g[x][y]==0){
                //左边四个是看看此位置出界了没有,第五个判断是否走过,最后判断是不是通路
                d[x][y] = d[t.x][t.y] + 1;//这点的距离表示离原点的距离
                q[++ tt] = {x, y};//将原来的点踢出取,另结新欢,将新娘子娶进来
            }
        }

    }
    return d[n - 1][m - 1];//返回出口位置,如果走不到出口,就返回-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;
}

第二个题解,用queue来解决问题

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

#define x first
#define y second

const int N = 110;

int n, m;
int g[N][N];//记录地图
int d[N][N];//作用1:验证是否走过,作用2表示始点到当前位置的最短距离

int bfs(){
    queue<PII> q;
    memset(d, -1, sizeof d);//bfs讲求最短,如果走之前走过的路,就不叫最短了,所以用-1来
    //标记一下,如果遍历到它的时候,看一下是否为-1,就知道它是否之前走过了

    d[0][0] = 0;//初始的位置,走的距离为0
    q.push({0, 0});//将队头放进去

    int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};//进行上下左右的移动

    while (q.size()){//直到所有的路都走了,也就停止了
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 4; i ++ ){
            int x = t.x + dx[i], y = t.y + dy[i];

            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){
                q.push({x, y});
                d[x][y] = d[t.x][t.y] + 1;
            }
        }
    }

    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;
}

版权声明:本文为qq_45914558原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。