用c++编写一个程序(图的建立与遍历) 1、根据给定图写出无向图的邻接矩阵; 2、写出无向图的深度优先搜索序列和广度优先搜索序列; 3、根据给定图写出有向图的邻接表; 4、实现图的邻接矩阵表示并建立一个无向图的邻接矩阵; 5、深度优先搜索整个图,广度优先搜索整个图。
时间: 2025-01-05 08:46:21 浏览: 102
好的,我来为您编写一个C++程序,实现图的建立与遍历功能。这个程序将包括您提到的所有要求。
```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph {
private:
int numVertices;
vector<vector<int>> adjMatrix;
vector<vector<int>> adjList;
vector<bool> visited;
public:
Graph(int vertices) {
numVertices = vertices;
adjMatrix.resize(vertices, vector<int>(vertices, 0));
adjList.resize(vertices);
visited.resize(vertices, false);
}
void addEdge(int i, int j) {
adjMatrix[i][j] = 1;
adjMatrix[j][i] = 1; // 对于无向图
adjList[i].push_back(j);
adjList[j].push_back(i); // 对于无向图
}
void printAdjMatrix() {
cout << "邻接矩阵:" << endl;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
void DFS(int vertex) {
visited[vertex] = true;
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
int adjVertex = adjList[vertex][i];
if (!visited[adjVertex])
DFS(adjVertex);
}
}
void BFS(int startVertex) {
vector<bool> visited(numVertices, false);
queue<int> q;
visited[startVertex] = true;
q.push(startVertex);
while (!q.empty()) {
int vertex = q.front();
q.pop();
cout << vertex << " ";
for (int i = 0; i < adjList[vertex].size(); i++) {
int adjVertex = adjList[vertex][i];
if (!visited[adjVertex]) {
visited[adjVertex] = true;
q.push(adjVertex);
}
}
}
}
void printAdjList() {
cout << "邻接表:" << endl;
for (int i = 0; i < numVertices; i++) {
cout << i << ": ";
for (int j = 0; j < adjList[i].size(); j++) {
cout << adjList[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
int numVertices = 5;
Graph g(numVertices);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.printAdjMatrix();
cout << endl;
cout << "深度优先搜索序列: ";
g.DFS(0);
cout << endl << endl;
cout << "广度优先搜索序列: ";
g.BFS(0);
cout << endl << endl;
g.printAdjList();
return 0;
}
```
这个程序实现了以下功能:
1. 根据给定图写出无向图的邻接矩阵。
2. 实现了深度优先搜索(DFS)和广度优先搜索(BFS)算法。
3. 根据给定图写出有向图的邻接表。
4. 实现了图的邻接矩阵表示并建立一个无向图的邻接矩阵。
5. 对整个图进行了深度优先搜索和广度优先搜索。
程序中,我们首先定义了一个Graph类,其中包含邻接矩阵和邻接表的表示,以及DFS和BFS的实现。在main函数中,我们创建了一个包含5个顶点的图,并添加了一些边。最后,我们打印出邻接矩阵,执行DFS和BFS,并打印出邻接表。
阅读全文
相关推荐


















