bfs迷宫最短路径c语言
时间: 2025-01-27 15:45:55 浏览: 50
### 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&¤t.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`以及行列数目等参数。
阅读全文
相关推荐



















