用于解决最短路问题,但是不是所有的最短路问题都可以用BFS来做,它只适用于每条边的权重都是1时
基本框架:
quene.push_back(initial_state)
while(!quene.empty()){
取出队头;
拓展对头;
}
BFS时间复杂度分析:BFS图搜时每个节点和每条边都只会遍历一次,所以其时间复杂度为O(n+m)。
AcWing 844. 走迷宫
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
int g[N][N], d[N][N];
int bfs(){
queue<PII> q;
memset(d, -1, sizeof d);
d[0][0] = 0;
q.push({0, 0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
while(!q.empty()){
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int x = t.first + dx[i], y = t.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0){
d[x][y] = d[t.first][t.second] + 1;
q.push({x, y});
}
}
}
return d[n - 1][m - 1];
}
int main(){
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%d", &g[i][j]);
}
}
cout << bfs() << endl;
return 0;
}
AcWing 845.八数码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int bfs(string start){
queue<string> q;
unordered_map<string, int> d;
q.push(start);
d[start] = 0;
string end = "12345678x";
while(!q.empty()){
auto t = q.front();
q.pop();
int distance = d[t];
if(t == end) return distance;
int k = t.find('x');
int x = k / 3, y = k % 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){
swap(t[k], t[a * 3 + b]);
if(!d.count(t)){
d[t] = distance + 1;
q.push(t);
}
swap(t[k], t[a * 3 + b]);
}
}
}
return -1;
}
int main(){
string start;
for(int i = 0; i < 9; i++){
string c;
cin >> c;
start += c;
}
cout << bfs(start) << endl;
return 0;
}