C++98版本以下,设计一个基于图的邻接表的图的基本操作的演示程序。 【基本要求】 实现下列六种基本运算:(1)创建图;(2)深度优先遍历图;(3)广度优先遍历图;(4)转换图的存储结构 分别在图的邻接矩阵和邻接表的存储结构实现
时间: 2024-12-13 16:24:50 浏览: 23
在C++98版本及之前,我们可以使用邻接表来表示图,并实现基本操作。这里是一个简单的邻接表表示和基础操作的示例:
```cpp
#include <iostream>
#include <vector>
// 图节点
struct Node {
int id;
std::vector<int> adjacents; // 邻接列表
};
// 创建图
void createGraph(Node** graph, int vertices, bool isAdjList = true) {
for (int i = 0; i < vertices; ++i) {
graph[i] = new Node{i};
if (isAdjList) { // 邻接列表
graph[i].adjacents.clear();
}
}
}
// 添加边(无向图)
void addEdge(Node* start, int dest, Node** graph) {
if (start->adjacents.find(dest) == std::vector<int>::npos) {
start->adjacents.push_back(dest);
if (dest != start) { // 避免自环
graph[dest]->adjacents.push_back(start); // 双向连接
}
}
}
// 深度优先搜索
void dfs(Node* node, std::vector<bool>& visited, Node** graph) {
visited[node->id] = true;
std::cout << node->id << " ";
for (int neighbor : node->adjacents) {
if (!visited[neighbor]) {
dfs(graph[neighbor], visited, graph);
}
}
}
// 广度优先搜索
void bfs(Node* root, std::vector<Node*>& queue, std::vector<bool>& visited, Node** graph) {
queue.push_back(root);
visited[root->id] = true;
while (!queue.empty()) {
Node* current = queue.front(); queue.pop();
std::cout << current->id << " ";
for (int neighbor : current->adjacents) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push_back(graph[neighbor]);
}
}
}
}
// 转换存储结构(假设已经存在邻接矩阵)
void convertToAdjacencyMatrix(Node** graph, int vertices) {
for (int i = 0; i < vertices; ++i) {
for (int j = 0; j < vertices; ++j) {
if (graph[i]->adjacents.find(j) != std::vector<int>::npos) {
graph[j]->adjacencies.push_back(i);
}
}
}
}
int main() {
int vertices = 5;
Node** graph = new Node*[vertices];
createGraph(graph, vertices);
// 添加边
addEdge(graph[0], 1, graph);
addEdge(graph[0], 3, graph);
addEdge(graph[1], 2, graph);
addEdge(graph[2], 4, graph);
// 操作演示
std::vector<bool> visited(vertices, false);
std::vector<Node*> queue;
std::cout << "Depth First Search (DFS): ";
dfs(graph[0], visited, graph);
std::cout << "\nBreadth First Search (BFS): ";
bfs(graph[0], queue, visited, graph);
// 示例转换为邻接矩阵
convertToAdjacencyMatrix(graph, vertices);
std::cout << "\nAfter conversion to Adjacency Matrix:\n";
// 输出邻接矩阵内容(此处省略实际打印,因为矩阵通常是非对称的)
return 0;
}
```
注意:这个示例仅展示了基本操作的实现,对于大型或复杂的应用,可能需要添加错误处理和优化。此外,邻接矩阵部分省略了实际的矩阵打印,因为那将涉及到更多的数组操作。
阅读全文