cpp1.创建一个无向图(采用邻接矩阵或者邻接表方式存储);2.分别输出从结点0开始的一个深度优先遍历序列和一个广度优先遍历序列。
时间: 2025-01-21 11:29:07 浏览: 42
好的,我来为您介绍如何在C++中实现无向图的创建以及深度优先遍历和广度优先遍历。
首先,我们将使用邻接表的方式来存储无向图。然后,我们将实现深度优先遍历(DFS)和广度优先遍历(BFS)算法。
以下是实现代码:
```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 定义图的邻接表表示
class Graph {
private:
int numVertices;
vector<vector<int>> adjLists;
vector<bool> visited;
public:
Graph(int vertices) {
numVertices = vertices;
adjLists.resize(numVertices);
visited.resize(numVertices, false);
}
void addEdge(int src, int dest) {
adjLists[src].push_back(dest);
adjLists[dest].push_back(src); // 无向图,所以两个方向都要添加
}
void DFS(int vertex) {
visited[vertex] = true;
cout << vertex << " ";
for (int i : adjLists[vertex]) {
if (!visited[i])
DFS(i);
}
}
void BFS(int startVertex) {
vector<bool> visited(numVertices, false);
queue<int> q;
visited[startVertex] = true;
q.push(startVertex);
while (!q.empty()) {
int currentVertex = q.front();
cout << currentVertex << " ";
q.pop();
for (int i : adjLists[currentVertex]) {
if (!visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
}
};
int main() {
Graph g(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);
cout << "深度优先遍历(DFS)序列: ";
g.DFS(0);
cout << endl;
cout << "广度优先遍历(BFS)序列: ";
g.BFS(0);
cout << endl;
return 0;
}
```
这段代码实现了以下功能:
1. 使用邻接表创建了一个无向图。
2. 实现了深度优先遍历(DFS)算法。
3. 实现了广度优先遍历(BFS)算法。
在 `main` 函数中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们分别调用了 `DFS` 和 `BFS` 方法,从顶点0开始进行遍历,并输出遍历序列。
阅读全文
相关推荐



















