搜索入门——BFS之走迷宫

BFS也称为宽度优先搜索,也是一种暴力搜索算法。BFS类似于以一个点为起点,一层一层向外扩展,就像是一个石子落入水里,荡起的涟漪一层一层向外散开。BFS不但可以完成DFS的功能,还能找到无权图最短路、迷宫最短路径等等。只是BFS相对于DFS而言需要借助于队列来辅助实现,实现上没有DFS那么无脑。
接下来我们看一个走迷宫的问题:
问题描述
在这里插入图片描述
输入:
(S表示迷宫起点,T表示终点)
10 10
#S######.#
…#…#
.#.##.##.#
.#…
##.##.####
…#…#
.#######.#
…#…
.####.###.
…#…G#
输出:
22

直接看下程序,具体解释都在注释里面:

#include <bits/stdc++.h>
using namespace std;

const int INF=1e+8;
const int maxn = 101;
const int maxm = 101;

char maze[maxn][maxm];
int N, M;
int sx, sy; // 起点坐标
int gx, gy; // 终点坐标
int d[maxn][maxm]; // 记录起点到各个位置最短距离的数组

int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}; // 四个方向移动

// 求从(sx,sy)到(gx, gy)的最短距离,若无法到达,则返回INF
int BFS()
{
    queue<pair<int, int> > que; // 利用队列这个辅助数据结构
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<M; j++){
            d[i][j] = INF; // 初始化
        }
    }
    que.push(make_pair(sx, sy));
    d[sx][sy] = 0;
    while(que.size())
    {
        pair<int, int> p = que.front(); // 取出队首元素放在中间变量p中
        que.pop();
        if(p.first==gx && p.second==gy) break;
        for (int i=0; i<4; i++)
        {
            int nx = p.first+dx[i];
            int ny = p.second+dy[i];
            if( 0<=nx && nx<N
                    && 0<=ny && ny<M
                    && maze[nx][ny] !='#'
                    && d[nx][ny]==INF)  // INF表示该位置未被访问
            {
                que.push(make_pair(nx, ny));
                d[nx][ny] = d[p.first][p.second]+1;
            }
        }
    }
    return d[gx][gy];
}
int main()
{
    cin >> N >> M;
    for(int i=0 ;i<N; i++)
    {
        for (int j = 0; j < M; ++j) {
            cin >> maze[i][j];
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if(maze[i][j] == 'S')
            {
                sx = i;
                sy = j;
            }
            if(maze[i][j] == 'G')
            {
                gx = i;
                gy = j;
            }
        }
    }
    cout << BFS() << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40438165/article/details/82967972
今日推荐