BFS经典例题:Maze迷宫

这是一篇关于使用BFS(广度优先搜索)解决迷宫问题的博客,探讨如何找到从起点到终点的最短路径。在迷宫中,只能向上下左右四个方向移动,遇到障碍物(如岩石、岩浆)则无法通行。输入包含迷宫的尺寸和地图,输出为从起点到终点的最短步数,若无解则输出-1。解题策略包括使用BFS算法,并通过结构体记录每一步的位置和步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are provided a maze(迷宫), and you need to program to find the least steps to walk from the start to the end.And you can only walk in four directions:up, down,left, right.

There will only be 5 kinds of characters in the maze.The meaning of each is as followed.

“#” is for rock, which you can not walk through.

“S” is for start.

“E” is for end.

“.” is for road.

“!” is for magma(岩浆),which you can not walk through.

Input
n,m represent the maze is a nxm maze.
n rows, m columns ,n、m are less than 21.

Then is the maze.

e.g.
这里写图片描述

Output

You need to give the least steps to walk from start to the end.If it doesn’t exist, then output -1.

e.g.(for the example in input)
4

解题思路:
广度优先搜索BFS。
下面是解决代码:

#include "iostream"
#include "string"
#include "queue"
using namespace std;
struct point {
    int x;
    int y;
    int step;
};
int num, dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
int row, col;
bool is_IN(int x, int y) {
    if (x < 0 || y < 0 || x > row || y > col)
        return false;
    return true;
}
int BFS(char arr[21][21], point start, point end) {
    point temp, New;
    queue<point> r;
    arr[start.x][start.y] = '#';
    r.push(start);
    while (!r.empty()) {
        temp = r.front();
        r.pop();
        if (temp.x == end.x && temp.y == end.y) {
            return temp.step;
        } else {
            for (int i = 0; i < 4; ++i) {
                New.x = temp.x + dx[i];
                New.y = temp.y + dy[i];
                if (is_IN(New.x, New.y) && (arr[New.x][New.y] == '.' || arr[New.x][New.y] == 'E')) {
                    arr[New.x][New.y] = '#';
                    New.step = temp.step + 1;
                    r.push(New);
                }
            }
        }
    }
    return -1;
}
int main() {
    cin >> row >> col;
    char arr[21][21];
    for (int i = 0; i < 21; ++i)
        for (int j = 0; j < 21; ++j)
            arr[i][j] = 0;
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
            cin >> arr[i][j];
    point start, end;
    start.step = 0;
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j) {
            if (arr[i][j] == 'S') {
                start.x = i;
                start.y = j;
            } else if (arr[i][j] == 'E') {
                end.x = i;
                end.y = j;
            }
        }
    int min = BFS(arr, start, end);
    cout << min << endl;
    return 0;
}

值得注意的几点:
1、走过的路要记得做好标记。
2、选用一个struct结构来记录每一步的位置比较清晰,而且在struct里面定义一个step来记录每一步是当前走过的第几步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值