基于循环队列的BFS原理及实现

1.故事起源

有一只蚂蚁出去寻找食物,无意中进入了一个迷宫。蚂蚁只能向上、下、左、右4个方向走,迷宫中有墙和水的地方都无法通行。这时蚂蚁犯难了,怎样才能找出到食物的最短路径呢?

2.思考

蚂蚁在起点时,有4个选择,可以向上、下、左、右某一个方向走1步。

如果蚂蚁走过了一段距离,此时也依然只有4个选择。
当然要排除之前走过的地方(不走回头路,走了也只会更长)和无法通过的墙和水。

蚂蚁想,还好我会影分身。如果每一步都分身成4个蚂蚁,向4个方向各走1步,这样最先找到食物的肯定就是最短的路径了(因为每一步都把能走的地方都走完了,肯定找不出更短的路径了)。

而且还能看出,第1步会到达所有到起点距离为1的地方,第2步也会到达所有距离为2的地方。
如此类推,第n步会覆盖所有到起点最短距离为n的地方。

3.问题建模

把迷宫地图放在二维数组中,能通行的地方为0,墙和水的地方为负数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于队列实现BFS算法的C语言代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_QUEUE_SIZE 1000 typedef struct { int x; int y; } Point; typedef struct { Point data[MAX_QUEUE_SIZE]; int front; int rear; } Queue; void initQueue(Queue *q) { q->front = -1; q->rear = -1; } int isEmpty(Queue *q) { return (q->front == -1 && q->rear == -1); } int isFull(Queue *q) { return (q->rear + 1) % MAX_QUEUE_SIZE == q->front; } void enqueue(Queue *q, Point p) { if (isFull(q)) { printf("Error: Queue is full!\n"); exit(EXIT_FAILURE); } if (isEmpty(q)) { q->front = q->rear = 0; } else { q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; } q->data[q->rear] = p; } Point dequeue(Queue *q) { if (isEmpty(q)) { printf("Error: Queue is empty!\n"); exit(EXIT_FAILURE); } Point p = q->data[q->front]; if (q->front == q->rear) { q->front = q->rear = -1; } else { q->front = (q->front + 1) % MAX_QUEUE_SIZE; } return p; } void bfs(int **graph, int n, int start) { Queue q; initQueue(&q); int visited[n]; for (int i = 0; i < n; i++) { visited[i] = 0; } Point p = {start, 0}; visited[start] = 1; enqueue(&q, p); while (!isEmpty(&q)) { Point curr = dequeue(&q); printf("%d ", curr.x); for (int i = 0; i < n; i++) { if (graph[curr.x][i] == 1 && visited[i] == 0) { Point next = {i, curr.y + 1}; visited[i] = 1; enqueue(&q, next); } } } } int main() { int n = 8; int **graph = (int **)malloc(n * sizeof(int *)); for (int i = 0; i < n; i++) { graph[i] = (int *)malloc(n * sizeof(int)); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = 0; } } graph[0][1] = graph[1][0] = 1; graph[0][2] = graph[2][0] = 1; graph[1][3] = graph[3][1] = 1; graph[1][4] = graph[4][1] = 1; graph[2][5] = graph[5][2] = 1; graph[2][6] = graph[6][2] = 1; graph[4][7] = graph[7][4] = 1; bfs(graph, n, 0); return 0; } ``` 该代码是一个简单的BFS实现,图的邻接矩阵存储在一个二维数组中,函数 `bfs` 接受该二维数组、顶点数和起点编号作为参数,并输出遍历结果。在函数中使用了一个队列来辅助实现BFS。具体实现可参考代码注释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值