BFS拓展算法
一、最小步数模型(了解相关的康托展开)
例题1、八数码
本题中在BFS的搜索中队列所存储的元素转变为字符串,并且需要一个dist[state]表示从初始阶段转换到state的最小步数。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1000010;
unordered_map<string, int> dist;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
// 表示从begin到目标字符串的最小步数
int bfs(string begin) {
string end = "12345678x"; // 目标字符串
string q[N];
int hh = 0, tt = 0;
q[0] = begin; // 存入初始状态
dist[begin] = 0;
while (hh <= tt) {
string t = q[hh++];
if (t == end) return dist[t]; // 若转化为了目标字符串则直接输出最短距离
int distance = dist[t], index = t.find('x'); // distance 预先存储距离 index 表示t中x的为u的下标
int x = index / 3, y = index % 3; // 一维下标转化为二维下标
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= 3 || b < 0 || b >= 3) continue;
swap(t[index], t[3 * a + b]); // 枚举所有能换位的数字或x
if (!dist.count(t)) {
dist[t] = distance + 1;
q[++tt] = t;
}
swap(t[index], t[3 * a + b]); // 再恢复初始阶段
}
}
return -1;
}
int main() {
string begin;
for (int i = 0; i < 9; i++) {
char str[2];
scanf("%s", str);
begin += *str;
}
printf("%d\n", bfs(begin));
return 0;
}
例题2、Acwing 1107. 魔板
与上一题类似,区别在于其转台的转化方式的改变,因此只需要在便利队列中修改一下状态转移方式即可。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e6 + 10;
string begin, end;
unordered_map<string, pair<char, string>> map; // 表示从上一状态转变为当前状态所需要的操作以及上一层的状态
unordered_map<string, int> dist; // dist[strs] 表示从 begin 转移至 strs 的最小步数
char g[2][4]; // 将字符串转化为二维字符数组
// 字符串转化为二维数组
void turn_array(string state) {
for (int i = 0; i < 4; i++) g[0][i] = state[i];
for (int i = 0; i < 4; i++) g[1][i] = state[7 - i];
}
// 二维数组转化为字符串
string turn_str() {
string res;
for (int i = 0; i < 4; i++) res += g[0][i];
for (int i = 3; i >= 0; i--) res += g[1][i];
return res;
}
string move_0(string state) { // A:上下两行翻转
turn_array(state);
for (int i = 0; i < 4; i++) swap(g[0][i], g[1][i]);
return turn_str();
}
string move_1(string state) { // B:将最右一列转移到最左边
turn_array(state);
char str1 = g[0][3], str2 = g[1][3];
for (int i = 3; i >= 1; i--) {
g[0][i] = g[0][i - 1];
g[1][i] = g[1][i - 1];
}
g[0][0] = str1, g[1][0] = str2;
return turn_str();
}
string move_2(string state) { // C:中间4个顺时针旋转
turn_array(state);
char str = g[0][1];
g[0][1] = g[1][1];
g[1][1] = g[1][2];
g[1][2] = g[0][2];
g[0][2] = str;
return turn_str();
}
// 返回从 begin 到 end 的最小步数
int bfs(string begin, string end) {
if (begin == end) return 0;
string q[N];
int hh = 0, tt = 0;
q[0] = begin;
dist[begin] = 0;
// 搜索过程
while (hh <= tt) {
string t = q[hh++];
if (t == end) return dist[t];
string lines[3]; // 表示三种操作后的三种不同状态转移结果
lines[0] = move_0(t);
lines[1] = move_1(t);
lines[2] = move_2(t);
for (int i = 0; i < 3; i++) {
string state = lines[i];
if (!dist.count(state)) {
dist[state] = dist[t] + 1;
map[state] = {char(i + 'A'), t};
q[++tt] = state;
}
}
}
return -1;
}
int main() {
string begin, end;
for (int i = 0; i < 8; i++) {
int ch;
scanf("%d", &ch);
end += char(ch + '0');
}
for (int i = 1; i <= 8; i++) begin += char(i + '0');
// cout << begin << ' ' << end << endl;
int ans = bfs(begin, end);
printf("%d\n", ans);
// 迭代输出操作步骤
string res = "";
while (end != begin) {
res += map[end].first;
end = map[end].second;
}
reverse(res.begin(), res.end());
if (ans > 0) cout << res << endl;
return 0;
}
二、双端队列广搜
例题3、Acwing 175. 电路维修
本题使用了一个双端队列的优化方式,该操作所处理的具体问题是边权值为0或1的问题;而本题中,能否从当前位置转移至下一个位置,能则边权为0,反之为1。
这里参考了这篇题解中的图
将(n * m)的原图扩展为(n + 1) * (m + 1)的新图,新加了一排和一列,上图中的每一块就是题目中给的边,而我们新加的就是旁边的点;从(0, 0)出发,dx[4]和dy[4]为点与点之间的转移,ix[4]和iy[4]为点与块之间的转移,cs[4]表示点到点之间的路径表示。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 510, INF = 0x3f3f3f3f, M = 1e6 + 10;
int T, n, m;
char g[N][N];
int dist[N][N]; // dist[i][j] 表示从起点 (0, 0) 到 (i, j) 所需要调换路径的最小次数
bool st[N][N]; // st[i][j] 表示 (i, j) 是走过的点
int bfs() {
deque<PII> q;
memset(dist, 0x3f, sizeof dist);
memset(st, 0, sizeof st);
q.push_back({0, 0});
dist[0][0] = 0;
// 方向变量
int dx[4] = {-1, -1, 1, 1}, dy[4] = {-1, 1, 1, -1};
int ix[4] = {-1, -1, 0, 0}, iy[4] = {-1, 0, 0, -1};
char cs[] = "\\/\\/";
while (!q.empty()) {
PII t = q.front();
q.pop_front();
if (st[t.x][t.y]) continue;
st[t.x][t.y] = true;
for (int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 0 || a > n || b < 0 || b > m) continue;
int ca = t.x + ix[i], cb = t.y + iy[i];
int distance = dist[t.x][t.y] + (g[ca][cb] != cs[i]);
if (distance < dist[a][b]) {
dist[a][b] = distance;
if (g[ca][cb] != cs[i]) q.push_back({a, b}); // 权值为 "0" 插入队头
else q.push_front({a, b}); // 权值为 "1" 插入队尾
}
}
}
return dist[n][m];
}
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%s", g[i]);
int res = bfs();
if (res == INF) puts("NO SOLUTION");
else printf("%d\n", res);
}
return 0;
}
三、双向广搜
该算法是为了在一般BFS超时的时候加快效率的,步骤就是设置两个队列分别存储初始状态和结尾状态,并且同时从开始和结尾两个方向相对搜索,当两方出现一个汇聚点的时候,就说明找到了最终答案、输出即可;该算法能够提高两倍的效率。
例题4、Acwing 190. 字串变换
就像上面说的步骤,从初始字符串和结尾字符串相对方向搜索即可。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 25;
string a[N], b[N];
int cnt;
int get(queue<string>& q, unordered_map<string, int>& dist, unordered_map<string, int>& dist_another, string a[], string b[]) {
auto t = q.front();
q.pop();
// 找能够转换的字符串片段
for (int i = 0; i < t.size(); i++) {
for (int j = 0; j < cnt; j++) {
if (t.substr(i, a[j].size()) == a[j]) { // 如果找到能够替换的字符串片段则直接替换
string state = t.substr(0, i) + b[j] + t.substr(i + a[j].size()); // 此时 a[j] 被替换为 b[j]
if (dist_another.count(state)) return dist[t] + dist_another[state] + 1; // 如果另一方向的搜索中存在则直接输出结果
if (dist.count(state)) continue; // 如果之前遍历过则跳过
dist[state] = dist[t] + 1;
q.push(state);
}
}
}
return 11;
}
int bfs(string& begin, string& end) {
if (begin == end) return 0;
queue<string> qa, qb; // 一个是正向宽搜,一个是逆向宽搜
qa.push(begin), qb.push(end);
unordered_map<string, int> dista, distb; // 一个是从起点起的最小次数 一个是从终点起的最小次数
dista[begin] = 0, distb[end] = 0;
while (qa.size() && qb.size()) {
int res;
if (qa.size() <= qb.size()) res = get(qa, dista, distb, a, b);
else res = get(qb, distb, dista, b, a);
if (res <= 10) return res;
}
return 11; // > 10 的答案为非法答案
}
int main() {
string begin, end;
cin >> begin >> end;
while (cin >> a[cnt] >> b[cnt]) cnt++;
int res = bfs(begin, end);
if (res > 10) puts("NO ANSWER!");
else printf("%d\n", res);
return 0;
}
四、A*算法
该算法使用范围比较小,算法核心在于需要先设置一个预估值,根据预估值的大小提高效率;操作就是,在正常的BFS队列遍历中,将一般队列换成优先队列,在队列中存入全程最小预估距离 = 真实距离 + 预估距离,真实距离表示从起始状态到当前状态的距离,预估距离表示当前状态到终止状态的距离,依次为依据遍历所有临边的全程最小预估距离。
该算法的条件为必须有解,因此需要先将无解的情况特判一下。
例题5、Acwing 179. 八数码
本题中的预估距离为曼哈顿距离,即为当前数字位置和当前数字应该在的位置之间的曼哈顿距离。存入优先队列的就是该预估曼哈顿距离和当前真实距离。
对于本题的特判无解情况为:逆序对数量必须为偶数。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
typedef pair<int, string> PIS;
// 返回从 state 到终点状态的预估值: 曼哈顿距离
int f(string state) {
int res = 0;
for (int i = 0; i < state.size(); i++) {
if (state[i] != 'x') {
int t = state[i] - '1';
// i 表示当前该数字的位置 t 表示该数字应该在的位置
res += abs(i / 3 - t / 3) + abs(i % 3 - t % 3);
}
}
return res;
}
string bfs(string start) {
priority_queue<PIS, vector<PIS>, greater<PIS>> heap; // 优先队列:小根堆,以全程最小预估距离为排序方案
unordered_map<string, pair<char, string>> prev; // 记录操作方案
unordered_map<string, int> dist; // 记录真实距离:从起点到当前状态
string end = "12345678x"; // 终止状态
heap.push({f(start), start});
dist[start] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
char cs[] = "urdl"; // 和移动方向对应的操作对应名称
while (heap.size()) {
auto t = heap.top();
heap.pop();
string state = t.second;
if (state == end) break; // 退出循环求方案
// 找到x所在位置
int x, y;
for (int i = 0; i < 9; i++) {
if (state[i] == 'x') {
x = i / 3, y = i % 3;
break;
}
}
string source = state; // 记录原始方案
// 进行移动
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= 3 || b < 0 || b >= 3) continue;
state = source; // 每次移动之前赋初值
swap(state[3 * x + y], state[3 * a + b]);
// 如果之前没有遍历过这个状态或者遍历过但是需要步数没有本次小则存入队列或重新赋值
if (!dist.count(state) || dist[state] > dist[source] + 1) {
dist[state] = dist[source] + 1;
prev[state] = {cs[i], source};
heap.push({dist[state] + f(state), state});
}
}
}
// 输出结果操作集合
string res;
while (end != start) {
res += prev[end].first;
end = prev[end].second;
}
reverse(res.begin(), res.end());
return res;
}
int main() {
string start, seq, ch;
while (cin >> ch) {
start += ch;
if (ch != "x") seq += ch; // 为了找逆序对
}
// 计算逆序对数量
int cnt = 0;
for (int i = 0; i < seq.size(); i++) {
for (int j = i + 1; j < seq.size(); j++) {
if (seq[i] > seq[j]) cnt++;
}
}
// A* 算法必须保证有解,而本题有解的要求是逆序对为偶数
if (cnt % 2) puts("unsolvable");
else cout << bfs(start) << endl; // ......
return 0;
}
例题6、Acwing 178. 第K短路
本题的预估值为从终点T起到所有其他点的最短距离,相当于做一遍Dijkstra算法。
本题无解特判情况为 没有边,但是至少需要有一条边才能进行算法操作。
代码展示:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
const int N = 10010, M = N * 2;
int n, m, S, T, K;
int e[M], ne[M], h[N], rh[N], w[M], idx;
int dist[N]; // dist[i] 表示点 i 到 T 的最短距离(预估值)
bool st[N];
void add(int h[], int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
// Dijkstra 算法求点 T 到其他所有点的最短距离作为预估值
void Dijkstra() {
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, T});
memset(dist, 0x3f, sizeof dist);
dist[T] = 0;
while (heap.size()) {
auto t = heap.top();
heap.pop();
int ver = t.y;
if (st[ver]) continue;
st[ver] = true;
// 遍历相邻点
for (int i = rh[ver]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[ver] + w[i]) {
dist[j] = dist[ver] + w[i];
heap.push({dist[j], j});
}
}
}
}
int A_star() {
priority_queue<PIII, vector<PIII>, greater<PIII>> heap; // 存储的是预估值,真实值以及当前点
heap.push({dist[S], {0, S}});
int cnt = 0; // 判断是否为第 K 次弹出的终点
while (heap.size()) {
auto t = heap.top();
heap.pop();
if (t.x >= 0x3f3f3f3f) return -1; // 排除不可能的情况,加快速度,算一个小优化
int ver = t.y.y, distance = t.y.x; // 变量表示当前点和真实距离
if (ver == T) cnt++; // 如果弹出终点,则次数加 1
if (cnt == K) return distance; // 弹出次数等于K,则表示为第K短的道路
for (int i = h[ver]; ~i; i = ne[i]) {
int j = e[i];
heap.push({distance + dist[j] + w[i], {distance + w[i], j}});
}
}
return -1;
}
int main() {
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
memset(rh, -1, sizeof rh);
for (int i = 0; i < m; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(h, a, b, c);
add(rh, b, a, c); // 求预估值 dist
}
scanf("%d%d%d", &S, &T, &K);
if (S == T) K++; // 由于至少是一条边,因此需要特判
Dijkstra();
printf("%d\n", A_star());
return 0;
}