迷宫问题(广度优先搜索)

本文介绍了一个基于广度优先搜索(BFS)算法解决迷宫最短路径问题的方法。通过定义一个5x5的二维数组表示迷宫,并使用1表示墙壁、0表示通路的方式,实现了从左上角到右下角的最短路径寻找。文中详细展示了C++实现的代码,包括如何遍历迷宫、记录路径等关键步骤。

定义一个二维数组:

int maze[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,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
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
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

这是一个简单的广度优先搜索问题,在编写程序的过程中要注意边界
上代码:

#include<iostream>    //广度优先搜索
#include<cstdio>
#include<cstring>
using namespace std;
int map[5][5];
int a[4] = { 1, -1, 0, 0 };  //方向
int b[4] = { 0, 0, -1, 1 };

struct stu    //放坐标用的结构体数组
{
    int row;
    int column;
}coordinate[2000];


int pre[100];
int visit[10][10];  //路线标记管理 1是走过

//输出函数
void print(int x)
{
    int t;
    t = pre[x];
    if (t == 0)
    {
        printf("(0, 0)\n");
        printf("(%d, %d)\n", coordinate[x].row, coordinate[x].column);
        return;
    }
    else
    {
        print(t);
        printf("(%d, %d)\n", coordinate[x].row, coordinate[x].column);
    }
}


void bfs()
{
    int head,tail;
    int x, y, x_, y_;
    memset(visit, 0, sizeof(visit));

    head = 0; tail = 1;
    coordinate[0].row = 0;
    coordinate[0].column= 0;
    pre[0] = -1;

    while (head < tail)
    {
        x = coordinate[head].row;
        y = coordinate[head].column;
        if (x == 4 && y == 4)  //右下角结束
        {
            print(head);
            return;
        }
        for (int i = 0; i < 5; i++)
        {
            x_ = x + a[i];
            y_ = y + b[i];

            if (visit[x_][y_] == 0 && x_ >= 0 && x_ <= 4 && y >= 0 && y <= 4 && map[x_][y_] == 0) //符合条件
            {
                visit[x_][y_] = 1; //标记
                coordinate[tail].row = x_;
                coordinate[tail].column = y_;
                pre[tail] = head;
                tail++;
            }
        }
        head++;
    }
    return;
}


int main()
{
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                scanf("%d", &map[i][j]);
            }
        }
        bfs();
    return 0;
}
### 迷宫问题中的广度优先搜索 (BFS) 算法 #### 定义与特性 广度优先搜索(BFS)是一种用于遍历或搜索树状图或图形结构的算法。此方法的特点是从根节点开始,沿着树的宽度移动,在每一层中尽可能深入地探索相邻子节点之前先访问同一级别的所有其他节点[^2]。 #### 主要步骤概述 对于迷宫问题而言,采用BFS意味着从入口位置作为起始点,逐步向外扩展至每一个可达的新格子,直到到达出口为止。具体操作如下: - 创建一个队列并将初始状态加入其中; - 当队列不为空时循环执行以下动作: - 取出当前队首元素并记录其坐标; - 对于该坐标的四个方向上的邻居依次尝试前进; - 如果遇到边界外或是障碍物则跳过; - 若未曾被访问过的空白区域,则将其标记为已访问,并放入队尾等待后续处理; - 终止条件:当成功抵达目标位置即结束;如果整个过程中未能触及终点说明无解。 #### Python代码实例 下面给出一段基于Python编写的简单版本的BFS求解迷宫最短路径程序: ```python from collections import deque def bfs(maze, start, end): rows = len(maze) cols = len(maze[0]) directions = [(0,-1), (-1,0), (0,1), (1,0)] # 左 上 右 下 queue = deque([start]) # 初始化队列为起点 visited = set() # 记录已经访问的位置集合 path = {start: None} # 存储前驱结点以便回溯构建最终路线 while queue: current_position = queue.popleft() if current_position == end: break for d in directions: next_x, next_y = current_position[0]+d[0], current_position[1]+d[1] if not ((0 <= next_x < rows and 0 <= next_y < cols)): continue # 边界检查 if maze[next_x][next_y] != 'O' or (next_x,next_y) in visited: # 非通路/已被访问过滤掉 continue queue.append((next_x, next_y)) visited.add((next_x, next_y)) # 加入待查列表&设置成已访态 path[(next_x, next_y)] = current_position # 更新父级关系表项 route = [] step_node = end # 自终点逆向追踪直至起点形成完整轨迹链 while step_node is not None: route.insert(0,step_node) step_node = path.get(step_node) return " -> ".join(f"({x},{y})" for x,y in route) if __name__ == "__main__": grid = [ ['X','X','X','X'], ['S','O','O','E'], ['X','X','X','X'] ] print(bfs(grid,(1,0),(1,3))) ``` 这段脚本定义了一个`bfs()`函数接收三个参数——表示迷宫的地图数组、代表起点座标元组以及目的地座标元组。通过运用双端队列(`deque`)高效管理待考察顶点序列,并利用字典对象维护各处的历史连接信息从而便于事后重构实际行走线路[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值