用c++自己确定一个简单无向图(顶点数>=5)利用邻接矩阵或者邻接表来实现图的构造,并完成: (1)用深度优先和广度优先两种算法对图进行遍历,输出顶点序列教据 (2)以合理的格式,输出各个顶点的邻接点。
时间: 2024-09-27 21:15:04 浏览: 39
在C++中,我们可以使用邻接矩阵或邻接表这两种数据结构来表示无向图。这里以邻接矩阵为例,因为它的操作效率适合于稠密图,即顶点间的边较多的情况。
```cpp
#include <iostream>
#include <vector>
// 邻接矩阵实现
typedef std::vector<std::vector<int>> AdjMatrix;
AdjMatrix createAdjMatrix(int vertices) {
AdjMatrix graph(vertices, std::vector<int>(vertices, 0)); // 初始化全零矩阵
// 替换这里的代码,添加实际的边,例如:
// graph[i][j] = 1; 表示顶点i和j之间有一条边
return graph;
}
void depthFirstSearch(AdjMatrix& graph, int start) {
std::vector<bool> visited(graph.size(), false);
std::cout << "Depth First Search:\n";
dfsUtil(graph, start, visited);
}
void dfsUtil(AdjMatrix& graph, int vertex, std::vector<bool>& visited) {
visited[vertex] = true;
std::cout << vertex << " ";
for (int i = 0; i < graph.size(); ++i)
if (!visited[i] && graph[vertex][i])
dfsUtil(graph, i, visited);
}
void breadthFirstSearch(AdjMatrix& graph, int start) {
std::vector<bool> visited(graph.size(), false);
std::queue<int> queue;
queue.push(start);
std::cout << "Breadth First Search:\n";
while (!queue.empty()) {
int vertex = queue.front();
queue.pop();
visited[vertex] = true;
std::cout << vertex << " ";
for (int i = 0; i < graph.size(); ++i)
if (!visited[i] && graph[vertex][i])
queue.push(i);
}
}
void printAdjacencyList(const AdjMatrix& graph) {
for (int i = 0; i < graph.size(); ++i) {
std::cout << "Adjacency list of vertex " << i << ":\n";
for (int j = 0; j < graph.size(); ++j)
if (graph[i][j]) {
std::cout << j << " ";
}
std::cout << "\n";
}
}
int main() {
int vertices;
std::cout << "Enter the number of vertices: ";
std::cin >> vertices;
AdjMatrix graph = createAdjMatrix(vertices);
std::cout << "Enter the edges or adjacency matrix elements:\n"; // 这里添加输入边的逻辑
depthFirstSearch(graph, 0); // 从顶点0开始深度优先搜索
breadthFirstSearch(graph, 0); // 同样从顶点0开始广度优先搜索
printAdjacencyList(graph);
return 0;
}
```
阅读全文