BFS
广度优先搜索(Breadth-First Search,下文简称为 BFS),其思想为”全局扩散”,在下文我们会重点介绍其拓展双向广搜和剪枝思想。
BFS 的基本实现
【例题 1】P1588 [USACO07OPEN] Catch That Cow S
这道题是经典的搜索题目,我们需要做以下三件事:
- 使用队列体现 BFS 的扩散效果;
- 尝试三种操作;
- 去重打标记。
事实上,去重打标记就是简单的剪枝。
代码如下,配有详细的注释:
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 200005;
bool vis[MAX_N]; // 注意数组大小要足够大,因为可能通过*2 操作超过 y
struct node {
int x; // 位置
int step; // 步数
};
int main() {
int t;
cin >> t;
while (t--) {
int x, y;
cin >> x >> y;
memset(vis, 0, sizeof vis); // 每次测试用例前初始化 vis 数组
queue<node> q;
q.push({x, 0});
vis[x] = 1; //注意标记
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.x == y) { //满足条件,跳出循环
cout << now.step << "\n";
break;
}
// 尝试三种操作
int next = now.x * 2;
if (next <= y * 2 && next < MAX_N && !vis[next]) { // 限制范围防止数组越界
vis[next] = 1;
q.push({next, now.step + 1});
}
next = now.x + 1;
if (next <= y * 2 && next < MAX_N && !vis[next]) {
vis[next] = 1;
q.push({next, now.step + 1});
}
next = now.x - 1;
if (next >= 0 && !vis[next]) {
vis[next] = 1;
q.push({next, now.step + 1});
}
}
}
return 0;
}在代码中的 vis 数组就是标记走过的格子,它们没有必要重复走,所以剪掉。这几乎是每一道搜索题都要做的事。
BFS 判断连通性问题
BFS 还有一个非常重要的用途:判断连通性。
问题就是求一共有多少个连通块。(这个连通块要求由非 0 字符组成)
这样说可能有点模糊,我们先以样例来分析:
4 10
0234500067
1034560500
2045600671
0000000089那么连通块就是下图标色部分,一共有 4 个细胞,没有问题。
考虑到 BFS 的思路是”全局扩散”,我们可以用 BFS 来实现:
- 具体来说就是寻找一个非
0的点,然后以这个点为起点 BFS,被搜到的点全部标记,直到队列空,然后找下一个没有被标记的点。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n, m;
struct node {
int x;
int y;
};
char a[105][105];
bool vis[105][105];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool check(int x, int y) {
if (vis[x][y]) { //如果被标记,返回 false
return 0;
}
if (x == 0 || x == n + 1 || y == 0 || y == m + 1) {//如果到了边界,返回 false
return 0;
}
if (a[x][y] == '0') { //如果不是细胞,返回 false
return 0;
}
return 1;
}
void bfs(int x, int y) {
queue<node>q;
q.push({x, y});
//vis[x][y] = 1;
while (!q.empty()) {
node now = q.front();
vis[now.x][now.y] = 1; //事实在 27 行写也可以
q.pop();
for (int i = 0; i < 4; i++) { //遍历 4 个方向,然后入队
if (check(now.x + dx[i], now.y + dy[i])) {
q.push({now.x + dx[i], now.y + dy[i]});
vis[now.x + dx[i]][now.y + dy[i]] = 1;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] != '0' && !vis[i][j]) {
bfs(i, j);
ans++; //每次搜索后,一定要记录答案
}
}
}
cout << ans;
return 0;
}预处理 BFS/BFS 的预处理
在执行实际查询前,预先进行一些 BFS 遍历,存储有用的信息(如距离、路径等),以便后续查询可以快速获取结果,就是预处理 BFS。
【例题 3】P12322 [蓝桥杯 2024 国 Java C] 瞬移
话不多说,先打暴力,思路非常简单:
- 对于每个位置状态,枚举每个 x,y,复杂度是 O(L×n^2 ),显然不行。
但是注意到 x,y 的取值只影响到了公式 (p+x+y−1) mod L+1,所以我们可以预处理所有 x+y 的值。
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull; //不用开 unsigned long long 也能过
const int N = 2005;
int n, L;
bool vis[N];
ull a[N];
struct node {
ull ps;
int step;
};
unordered_set<ull> init_a; //用 set 记录预处理的结果
void init_xy() { //预处理 x 和 y
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= n; y++) {
init_a.insert((a[x] + a[y]) % L);
}
}
}
void bfs() {
queue<node> q;
node front = {1, 0};
q.push(front);
while (!q.empty()) {
front = q.front();
q.pop();
if (front.ps == (ull)L) {
cout << front.step;
return;
}
for (auto it : init_a) {
ull now;
now = (front.ps + it - 1) % L + 1;
if (!vis[now]) {
vis[now] = 1; //记得标记
q.push({now, front.step + 1});
}
}
}
cout << "-1"; //如果队列空了还没有结果,输出 -1
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> L;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
init_xy();
bfs();
return 0;
}01BFS
在做这道题之前,我们先了解一下数据结构 deque:
STL deque
std::deque,双端队列。它允许在队列的两端高效地进行插入和删除操作。
clear()清除所有元素。insert()支持在某个迭代器位置插入元素、可以插入多个。复杂度与pos与两端距离较小者成线性。erase()删除某个迭代器或者区间的元素,返回最后被删除的迭代器。复杂度与insert一致。push_front()在头部插入一个元素,常数复杂度。pop_front()删除头部元素,常数复杂度。push_back()在末尾插入一个元素,常数复杂度。pop_back()删除末尾元素,常数复杂度。swap()与另一个容器进行交换,此操作是常数复杂度。
注意到代价有 0 和 1,可以用到01BFS。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int M = 1005;
int r, c;
int a[M][M];
int Q;
// 8 个方向的移动增量(北、东北、东、东南、南、西南、西、西北)
int go[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1},{1, 0}, {1, -1}, {0, -1}, {-1, -1}};
bool vis[M][M];
int step[M][M]; // 记录到达每个位置的最小能量消耗
struct pairs {
int x;
int y;
};
int bfs(int rs, int cs, int rd, int cd) {
// 初始化
memset(vis, 0, sizeof(vis));
memset(step, -1, sizeof(step));
deque<pairs> q; // 使用双端队列进行 0-1 BFS
q.push_back({rs, cs});
step[rs][cs] = 0; // 起点能量消耗为 0
vis[rs][cs] = 1;
while (!q.empty()) {
pairs u = q.front(); // 取出队首元素
q.pop_front();
// 尝试 8 个可能的移动方向
for (int i = 0; i < 8; i++) {
int xp = u.x + go[i][0]; // 计算新位置的行坐标
int yp = u.y + go[i][1]; // 计算新位置的列坐标
// 检查新位置是否越界
if (xp < 1 || xp > r || yp < 1 || yp > c) {
continue;
}
// 判断是否需要消耗能量
// 如果移动方向与水流方向一致,不消耗能量(add_step=0)
// 否则消耗 1 单位能量(add_step=1)
int add_step = (i == a[u.x][u.y]) ? 0 : 1;
// 如果新位置未被访问过,或者找到更优路径
if (step[xp][yp] == -1 || step[u.x][u.y] + add_step < step[xp][yp]) {
step[xp][yp] = step[u.x][u.y] + add_step;
// 根据能量消耗决定加入队列的方式
// 0 消耗加入队首(优先处理),1 消耗加入队尾
if (add_step == 0) {
q.push_front({xp, yp});
} else {
q.push_back({xp, yp});
}
}
}
}
return step[rd][cd]; // 返回到达终点的最小能量消耗
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> r >> c;
for (int i = 1; i <= r; i++) {
string s;
cin >> s;
for (int j = 1; j <= c; j++) {
a[i][j] = s[j - 1] - '0';
}
}
cin >> Q;
while (Q--) {
int rs, cs, rd, cd;
cin >> rs >> cs >> rd >> cd;
cout << bfs(rs, cs, rd, cd) << "\n";
}
return 0;
}双向广搜
双向广度搜索,在已知起点和终点的情况下,同时从起点和终点出发进行 BFS,当两边的搜索相遇时停止,从而减少搜索空间,提高效率。
这样说有点抽象,可以画一个图来理解:
在图中, 的点是起点和终点,它们通过 BFS 扩散,最终相遇,停止搜索。
我们仍然以该题目为例,由于起点和终点已知,可以用双向广搜。
本题的双向广搜方法:
- 双向 BFS:同时从起点和终点开始搜索,当两边的搜索相遇时即可确定最短路径
- 方向处理:使用两个数组
dx[8]和dy[8]表示 8 个方向的移动增量 - 反向移动:反向搜索时使用
(i+4)%8计算相反方向 - 能量计算:
- 顺流方向(移动方向与洋流方向一致):
0消耗。 - 其他方向:
1消耗。
- 顺流方向(移动方向与洋流方向一致):
时间复杂度: 。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
int r, c, q;
int g[N][N]; // 网格方向数据
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
struct P {
int x, y;
}; // 坐标结构体
int bfs(int sx, int sy, int ex, int ey) {
if (sx == ex && sy == ey) return 0;
// 初始化双向队列
deque<P> qf, qb; // 前向队列和反向队列
int df[N][N], db[N][N]; // 前向和反向距离
bool vf[N][N] = {0}, vb[N][N] = {0}; // 访问标记
memset(df, -1, sizeof df);
memset(db, -1, sizeof db);
// 设置起点和终点
qf.push_back({sx, sy});
qb.push_back({ex, ey});
df[sx][sy] = 0;
db[ex][ey] = 0;
vf[sx][sy] = 1;
vb[ex][ey] = 1;
while (!qf.empty() && !qb.empty()) {
// 选择较小的队列进行扩展
if (qf.size() <= qb.size()) {
auto t = qf.front();
qf.pop_front();
for (int i = 0; i < 8; i++) {
int nx = t.x + dx[i], ny = t.y + dy[i];
if (nx < 1 || nx > r || ny < 1 || ny > c) continue;
// 计算能量消耗
int cost;
if (i == g[t.x][t.y]) {
cost = 0; // 顺流方向不耗能
} else {
cost = 1; // 其他方向耗能 1
}
// 更新前向距离
if (!vf[nx][ny] || df[t.x][t.y] + cost < df[nx][ny]) {
df[nx][ny] = df[t.x][t.y] + cost;
vf[nx][ny] = 1;
// 根据能耗决定插入位置
if (cost == 0) {
qf.push_front({nx, ny}); // 0 耗能插队首
} else {
qf.push_back({nx, ny}); // 1 耗能插队尾
}
// 检查是否相遇
if (vb[nx][ny]) {
return df[nx][ny] + db[nx][ny];
}
}
}
} else {
auto t = qb.front();
qb.pop_front();
for (int i = 0; i < 8; i++) {
// 计算反向移动方向
int nx = t.x + dx[(i + 4) % 8], ny = t.y + dy[(i + 4) % 8];
if (nx < 1 || nx > r || ny < 1 || ny > c) continue;
// 计算反向能量消耗
int cost;
if ((i + 4) % 8 == g[t.x][t.y]) {
cost = 0; // 顺流方向不耗能
} else {
cost = 1; // 其他方向耗能 1
}
// 更新反向距离
if (!vb[nx][ny] || db[t.x][t.y] + cost < db[nx][ny]) {
db[nx][ny] = db[t.x][t.y] + cost;
vb[nx][ny] = 1;
// 根据能耗决定插入位置
if (cost == 0) {
qb.push_front({nx, ny});
} else {
qb.push_back({nx, ny});
}
// 检查是否相遇
if (vf[nx][ny]) {
return df[nx][ny] + db[nx][ny];
}
}
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> r >> c;
for (int i = 1; i <= r; i++) {
string s;
cin >> s;
for (int j = 1; j <= c; j++) {
g[i][j] = s[j - 1] - '0';
}
}
cin >> q;
while (q--) {
int sx, sy, ex, ey;
cin >> sx >> sy >> ex >> ey;
cout << bfs(sx, sy, ex, ey) << "\n";
}
return 0;
}
