BFS (迷宫的最短路径)

 


迷宫的最短路径

给定一个大小为N * M 的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点 。

限制条件: N , M<=100 。( # . S G  分别代表 墙壁、通道、起点和终点。)


sample input 

10 10

# S # # # # # # . #
. . . . . . # . . #
. # . # # . # # . #
. # . . . . . . . .
# # . # # . # # # #
. . . . # .
### BFS算法用于求解迷宫最短路径 广度优先搜索(BFS)是一种逐层遍历图结构的方式,在处理无权图中的最短路径问题时非常有效[^1]。对于迷宫而言,可以将其视为一个二维数组表示的网格地图,其中0代表可通过的位置而1则代表障碍物。 下面是一个使用C语言实现基于队列的BFS来查找从起点到终点最短路径的例子: ```c #include <stdio.h> #define MAX 100 int queue[MAX * MAX], front = -1, rear = -1; int visited[MAX][MAX]; char maze[MAX][MAX]; typedef struct { int x, y; } Point; // 判断位置是否合法 int isValid(int row, int col, int rows, int cols) { return (row >= 0 && row < rows && col >= 0 && col < cols); } void enqueue(Point p) { if(rear == MAX*MAX-1){ printf("Queue is full\n"); return; } queue[++rear]=p.x*p.cols+p.y; // 将坐标转换成一维索引存储 } Point dequeue() { Point temp={queue[front]/cols, queue[front]%cols}; ++front; return temp; } int isEmpty(){ return front>rear; } void bfs(char maze[][MAX], int startRow, int startCol, int endRow, int endCol, int rows, int cols) { Point src = {startRow, startCol}, dest = {endRow, endCol}; // 初始化访问标记矩阵 for (int i=0;i<rows;++i) for (int j=0;j<cols;++j) visited[i][j]=0; enqueue(src); while (!isEmpty()) { Point current = dequeue(); if(current.x==dest.x&&current.y==dest.y){ printf("Found the exit at (%d,%d)\n", dest.x, dest.y); break; } // 上下左右四个方向移动尝试 int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; for (int k = 0; k < 4; ++k) { int newRow=current.x+dx[k], newCol=current.y+dy[k]; if(isValid(newRow,newCol,rows,cols)&&!visited[newRow][newCol]&&maze[newRow][newCol]!='1'){ visited[newRow][newCol]=visited[current.x][current.y]+1; Point nextPos={newRow, newCol}; enqueue(nextPos); } } } } ``` 此代码片段展示了如何利用队列数据结构执行标准形式下的宽度优先搜索过程,并记录到达每个节点所需的步数以便最终确定最短距离。注意这里假设输入的是字符型迷宫布局('0'为空白,'1'为墙壁),并且已经预定义好了最大尺寸`MAX`以及行列数目等参数。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值