c++什么是多源bfs
时间: 2025-01-06 07:03:32 浏览: 56
多源BFS(Breath-First Search,广度优先搜索)是一种图搜索算法,类似于普通的BFS,但它可以从多个起点同时开始搜索。多源BFS常用于解决需要找到图中所有点到某些特定点的最短距离或路径的问题。
以下是多源BFS的基本步骤:
1. **初始化**:将所有起点加入队列,并设置它们的初始距离为0。
2. **标记访问**:将所有起点标记为已访问。
3. **广度优先搜索**:从队列中取出一个节点,检查其所有邻居。如果邻居未被访问,则将其加入队列,并更新其距离。
4. **重复步骤3**,直到队列为空。
多源BFS的优点在于它可以一次性处理多个起点,避免了多次运行单源BFS的冗余计算。
### 示例代码
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
const int MAX = 1000;
vector<vector<int>> graph(MAX, vector<int>());
vector<int> distance(MAX, -1);
void multiSourceBFS(vector<int>& sources) {
queue<int> q;
for (int source : sources) {
q.push(source);
distance[source] = 0;
}
while (!q.empty()) {
int current = q.front();
q.pop();
for (int neighbor : graph[current]) {
if (distance[neighbor] == -1) {
distance[neighbor] = distance[current] + 1;
q.push(neighbor);
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
vector<int> sources = {0, 1, 2}; // 示例起点
multiSourceBFS(sources);
for (int i = 0; i < n; ++i) {
cout << "Distance from sources to node " << i << " is " << distance[i] << endl;
}
return 0;
}
```
### 解释
1. **图的表示**:使用邻接表表示图。
2. **初始化**:将所有起点加入队列,并设置它们的初始距离为0。
3. **广度优先搜索**:从队列中取出一个节点,检查其所有邻居。如果邻居未被访问,则将其加入队列,并更新其距离。
4. **输出结果**:最终每个节点的距离数组中存储的是从起点到该节点的最短距离。
阅读全文
相关推荐




















