浅谈·BFS

· · 算法·理论

引入

首先我们先看一个例题:

::::info[题面]

题目描述

有一个 m \times n 的迷宫,用 1 表示障碍,0 表示可以走,从起点出发可以往上下左右四个方向走。请问到达终点的最短步数是多少?(n,m \le 100)

输入格式

输入第一行两个整数 n,m 代表迷宫的长和宽。
接下来的 n 行 m 列,一个 0-1矩阵代表迷宫。
之后的一行代表起点的行和列。
最后一行代表终点的行和列。

输出格式

一个数字,代表到达终点的最短步数。

样例输入

5 6
0 1 1 0 1 0
0 0 0 1 0 0
1 1 0 0 0 1
0 1 0 0 0 1
0 0 1 1 0 0
1 1
5 6

样例输出

9

样例说明

::::

Solution

刚学过深搜的OIer一定会想到DFS,但我们还有没有其他办法呢?

答案是肯定的,那就是今天要讲的 BFS。

$A$ : 广度优先搜索($Breadth First Search$,简称 $BFS$)是由近及远的搜索解。不同于深度优先搜索的一条路走到底再换另一条路。这种算法往往通过队列来实现。 $Q$ : 什么是队列? $A$ : [队列($FIFO$,$First$ $In$ $First$ $Out$)](https://oi-wiki.org/ds/queue/),是一种先进先出的数据结构。 ### $DFS$ 与 $BFS$ 的不同 同一棵树🌲,通过 $DFS$ 和 $BFS$ 遍历到的顺序编号,它的节点的编号会有所不同,例如以下两个图片,每个节点的编号代表它被遍历到的顺序: #### DFS图片 ![深搜图片](https://cdn.luogu.com.cn/upload/image_hosting/1fa10esq.webp) #### BFS图片 ![广搜图片](https://cdn.luogu.com.cn/upload/image_hosting/2khk0w2i.webp) *** $Q$ : 那 $BFS$ 怎么实现呢? $A$ : * 广搜我们一般使用队列辅助实现,最初队列只有一个初始的起点。 * 每一轮我们取出队头的点,然后扩展可能的状态进入队尾,最后把队头元素弹出。 * 如果队头状态无法扩展出新状态,队尾不变,结束后队头出队。 * 当队列为空,也就是所有队伍中的元素都已经扩展,此时搜索结束。 **按照上面的方法,我们可以得到广搜的函数模板。** ```cpp line-numbers int bfs(int x,int y) { queue<node> q; //定义一个队列 q.push((node){x,y,0}); //首先加入初始节点,记录坐标和长度 while(!q.empty()) //队列非空 { node t = q.front(); //取出队头的节点 q.pop(); //删除队头 for(int i = 0;i < 4;i++) { int nx = t.x + dx[i],ny = t.y + dy[i]; //方向数组更新下一个节点的坐标 if(nx <= n && nx >= 1 && ny <= m && ny >= 1 && a[nx][ny] == 0) //如果没走出界并且没访问过 { a[nx][ny] = 1; //标记为访问过 if(nx == x3 && ny == y3) return t.s + 1; //如果走到目标节点则返回走过的长度 q.push((node){nx,ny,t.s + 1}); //否则把扩展后的节点信息加入队列 } } } } ``` 就这样,我们便可以补充完整全部代码(只展示伪代码)。 ```cpp line-numbers #include <bits/stdc++.h> using namespace std; bool a[10005][10005]; //存迷宫 int dx[4] = {1,-1,0,0}; int dy[4] = {0,0,1,-1}; //方向数组 int x3,y3; //终点坐标 int x2,y2; //起点坐标 int n,m; //图的长、宽 struct node { int x,y,s; }; //结构体 int bfs(int x,int y) { //······ } int main() { //输入m、n和迷宫、起点、终点 //调用函数 return 0; } /*样例 5 6 0 1 1 0 1 0 0 0 0 1 0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0 1 1 0 0 1 1 5 6 9 */ ``` 好了,内容都讲完了,接下来是习题时间。 - [P1588 [USACO07OPEN] Catch That Cow S](https://www.luogu.com.cn/problem/P1588) - [P1746 离开中山路](https://www.luogu.com.cn/problem/P1746) - [P1443 马的遍历](https://www.luogu.com.cn/problem/P1443) - [P1135 奇怪的电梯](https://www.luogu.com.cn/problem/P1135) - [P1451 求细胞数量](https://www.luogu.com.cn/problem/P1451) - [P4328 [COCI 2006/2007 #1] Slikar](https://www.luogu.com.cn/problem/P4328) - [P1747 好奇怪的游戏](https://www.luogu.com.cn/problem/P1747) - [P2802 回家](https://www.luogu.com.cn/problem/P2802) - [P6757 [BalticOI 2013] Tracks in the Snow](https://www.luogu.com.cn/problem/P6757) - [P1433 吃奶酪](https://www.luogu.com.cn/problem/P1433) - [P1032 [NOIP 2002 提高组] 字串变换(疑似错题)](https://www.luogu.com.cn/problem/P1032) - [P1825 [USACO11OPEN] Corn Maze S](https://www.luogu.com.cn/problem/P1825) - [P1332 血色先锋队](https://www.luogu.com.cn/problem/P1332)