string nodes[MAXN] = { "A", "B", "C", "D", "E", "F", "G" };//A-G对应0-6 vector<vector<int>> adjacencyList = { {5, 6}, {2, 6}, {1, 4}, {4, 6}, {2, 3, 5}, {0, 4, 6}, {0, 1, 3, 5} };根据上述代码C++实现广度优先搜索遍历,并输出所有遍历节点的值。
时间: 2023-06-27 18:02:53 浏览: 78
C++实现广度优先搜索实例
以下是C++实现广度优先搜索遍历的代码,并输出所有遍历节点的值:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 7;
string nodes[MAXN] = { "A", "B", "C", "D", "E", "F", "G" };
vector<vector<int>> adjacencyList = {
{5, 6},
{2, 6},
{1, 4},
{4, 6},
{2, 3, 5},
{0, 4, 6},
{0, 1, 3, 5}
};
void bfs(int start) {
bool visited[MAXN] = { false };
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
cout << nodes[node] << " ";
for (int i = 0; i < adjacencyList[node].size(); i++) {
int neighbor = adjacencyList[node][i];
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
int main() {
bfs(0);
return 0;
}
```
输出结果为:A F G E B C D
阅读全文