c++以邻接表作为存储结构建立一个无向图,按深度优先遍历该无向图,输出遍历序列; 按广度优先遍历该无向图,输出遍历序列
时间: 2024-12-13 20:19:22 浏览: 55
在C++中,我们通常使用邻接列表(Adjacency List)作为无向图的数据结构,因为它对于表示稀疏图(边的数量远小于顶点数量的平方)更高效。这里是一个简单的示例,我们将分别讲解如何使用深度优先搜索(DFS)和广度优先搜索(BFS)遍历这样的无向图:
**深度优先遍历(DFS)**:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 定义图的节点
struct Node {
int id;
vector<int> adj; // 邻接列表
};
void dfs(Node* node, vector<bool>& visited) {
visited[node->id] = true;
cout << node->id << " "; // 输出当前节点
for (int neighbor : node->adj) {
if (!visited[neighbor]) {
dfs(&nodes[neighbor], visited); // 递归访问未访问过的邻居
}
}
}
// 主函数
void traverseGraphDFS(vector<Node>& nodes) {
int n = nodes.size();
vector<bool> visited(n, false);
for (Node& node : nodes) {
if (!visited[node.id]) {
dfs(&node, visited);
cout << endl; // 每次遍历完一层,换行
}
}
}
int main() {
// 初始化节点和邻接列表
// ...
// 调用DFS遍历并输出结果
traverseGraphDFS(nodes);
return 0;
}
```
**广度优先遍历(BFS)**:
```cpp
#include <queue>
using namespace std;
void bfs(Node* root, vector<bool>& visited) {
queue<int> q;
q.push(root->id);
visited[root->id] = true;
while (!q.empty()) {
int current = q.front(); // 取出队首元素
cout << current << " "; // 输出当前节点
q.pop();
for (int neighbor : nodes[current].adj) { // 遍历邻居
if (!visited[neighbor]) {
q.push(neighbor);
visited[neighbor] = true;
}
}
}
}
void traverseGraphBFS(vector<Node>& nodes) {
int n = nodes.size();
vector<bool> visited(n, false);
bfs(&nodes[0], visited); // 从第一个节点开始
cout << endl; // 结束时换行
}
int main() {
// 初始化节点和邻接列表
// ...
// 调用BFS遍历并输出结果
traverseGraphBFS(nodes);
return 0;
}
```
请记住,你需要根据实际的节点数组`nodes`替换上述代码中的初始化部分,并处理好每个节点的连接。这两个函数会分别按照深度优先和广度优先的方式遍历并打印节点。
阅读全文
相关推荐


















