然后实现广度优先遍历c➕➕
时间: 2023-06-22 08:39:56 浏览: 89
C++的实现方式与Python类似,也是使用队列来实现广度优先遍历。下面是一个C++的实现示例:
```c++
#include <iostream>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
vector<int> bfs(unordered_map<int, vector<int>>& graph, int start) {
unordered_set<int> visited;
queue<int> q;
vector<int> res;
q.push(start);
visited.insert(start);
while (!q.empty()) {
int node = q.front();
q.pop();
res.push_back(node);
for (int neighbor : graph[node]) {
if (visited.count(neighbor) == 0) {
q.push(neighbor);
visited.insert(neighbor);
}
}
}
return res;
}
int main() {
unordered_map<int, vector<int>> graph;
graph[0] = {1, 2};
graph[1] = {0, 2, 3};
graph[2] = {0, 1, 3};
graph[3] = {1, 2, 4};
graph[4] = {3};
vector<int> res = bfs(graph, 0);
for (int node : res) {
cout << node << " ";
}
cout << endl;
return 0;
}
```
其中,graph是以unordered_map存储的图,key表示节点,value表示该节点的邻居节点列表。start是起始节点。函数返回一个vector,包含图中所有与起始节点连通的节点。
阅读全文