用c++编写程序实现以下功能: 1.创建一个无向图(采用邻接矩阵或者邻接表方式存储); 2.分别输出从结点0开始的一个深度优先遍历序列和一个广度优先遍历序列。
时间: 2025-01-27 16:16:23 浏览: 44
好的,下面是一个使用C++编写的程序,实现了一个无向图的创建,并分别输出从结点0开始的深度优先遍历序列和广度优先遍历序列。这里我们采用邻接表的方式存储无向图。
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
class Graph {
private:
int numVertices;
vector<vector<int>> adjList;
public:
Graph(int vertices) {
numVertices = vertices;
adjList.resize(numVertices);
}
void addEdge(int src, int dest) {
adjList[src].push_back(dest);
adjList[dest].push_back(src); // 无向图,所以要双向添加
}
void DFS(int startVertex) {
vector<bool> visited(numVertices, false);
stack<int> stack;
stack.push(startVertex);
while (!stack.empty()) {
int currentVertex = stack.top();
stack.pop();
if (!visited[currentVertex]) {
cout << currentVertex << " ";
visited[currentVertex] = true;
}
for (auto it = adjList[currentVertex].rbegin(); it != adjList[currentVertex].rend(); ++it) {
if (!visited[*it]) {
stack.push(*it);
}
}
}
}
void BFS(int startVertex) {
vector<bool> visited(numVertices, false);
queue<int> queue;
visited[startVertex] = true;
queue.push(startVertex);
while (!queue.empty()) {
int currentVertex = queue.front();
cout << currentVertex << " ";
queue.pop();
for (auto it = adjList[currentVertex].begin(); it != adjList[currentVertex].end(); ++it) {
if (!visited[*it]) {
visited[*it] = true;
queue.push(*it);
}
}
}
}
};
int main() {
int vertices, edges;
cout << "Enter number of vertices: ";
cin >> vertices;
cout << "Enter number of edges: ";
cin >> edges;
Graph graph(vertices);
cout << "Enter each edge (source and destination):" << endl;
for (int i = 0; i < edges; ++i) {
int src, dest;
cin >> src >> dest;
graph.addEdge(src, dest);
}
cout << "Depth First Traversal starting from vertex 0: ";
graph.DFS(0);
cout << endl;
cout << "Breadth First Traversal starting from vertex 0: ";
graph.BFS(0);
cout << endl;
return 0;
}
```
这个程序首先读取顶点数和边数,然后通过邻接表存储图。接着,程序分别调用深度优先遍历(DFS)和广度优先遍历(BFS)函数,从结点0开始进行遍历,并输出遍历序列。
阅读全文
相关推荐





