设图结点的元素类型为char,建立一个不少于8个顶点的带权无向图G,实现以下图的各种基本操作的程序: ① 用邻接矩阵作为储结构存储图G并输出该邻接矩阵; ② 用邻接链表作为储结构存储图G并输出该邻接链表; ③ 按DF
时间: 2024-02-16 21:05:20 浏览: 76
S算法遍历图G,并输出遍历结果。
好的,我明白了你的问题。以下是基于C++的程序代码实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 8;
const int INF = 0x3f3f3f3f;
// 邻接矩阵存储结构
int graph[MAXN][MAXN] = {
{0, 1, 1, INF, INF, INF, INF, INF},
{1, 0, INF, 1, 1, INF, INF, INF},
{1, INF, 0, INF, INF, 1, INF, INF},
{INF, 1, INF, 0, INF, INF, 1, INF},
{INF, 1, INF, INF, 0, INF, INF, 1},
{INF, INF, 1, INF, INF, 0, 1, INF},
{INF, INF, INF, 1, INF, 1, 0, 1},
{INF, INF, INF, INF, 1, INF, 1, 0}
};
// 邻接链表存储结构
struct Node {
int v;
int weight;
Node(int _v, int _w): v(_v), weight(_w) {}
};
vector<Node> graphList[MAXN];
// 添加边到邻接链表
void addEdge(int u, int v, int w) {
graphList[u].push_back(Node(v, w));
graphList[v].push_back(Node(u, w));
}
// 输出邻接矩阵
void printMatrix() {
for (int i = 0; i < MAXN; i++) {
for (int j = 0; j < MAXN; j++) {
if (graph[i][j] == INF) {
cout << "INF ";
} else {
cout << graph[i][j] << " ";
}
}
cout << endl;
}
}
// 输出邻接链表
void printList() {
for (int i = 0; i < MAXN; i++) {
cout << i << ": ";
for (Node node : graphList[i]) {
cout << node.v << "(" << node.weight << ") ";
}
cout << endl;
}
}
// 深度优先遍历
void dfs(int u, bool* visited) {
visited[u] = true;
cout << (char)('A' + u) << " ";
for (Node node : graphList[u]) {
int v = node.v;
if (!visited[v]) {
dfs(v, visited);
}
}
}
// DF S算法遍历
void dfsTraversal() {
bool visited[MAXN] = {false};
cout << "DFS Traversal: ";
for (int i = 0; i < MAXN; i++) {
if (!visited[i]) {
dfs(i, visited);
}
}
cout << endl;
}
int main() {
// 添加边到邻接链表
addEdge(0, 1, 1);
addEdge(0, 2, 1);
addEdge(1, 3, 1);
addEdge(1, 4, 1);
addEdge(2, 5, 1);
addEdge(3, 6, 1);
addEdge(4, 7, 1);
addEdge(5, 6, 1);
// 输出邻接矩阵
cout << "Adjacency Matrix:" << endl;
printMatrix();
cout << endl;
// 输出邻接链表
cout << "Adjacency List:" << endl;
printList();
cout << endl;
// DF S遍历
dfsTraversal();
return 0;
}
```
输出结果为:
```
Adjacency Matrix:
0 1 1 INF INF INF INF INF
1 0 INF 1 1 INF INF INF
1 INF 0 INF INF 1 INF INF
INF 1 INF 0 INF INF 1 INF
INF 1 INF INF 0 INF INF 1
INF INF 1 INF INF 0 1 INF
INF INF INF 1 INF 1 0 1
INF INF INF INF 1 INF 1 0
Adjacency List:
0: 1(1) 2(1)
1: 0(1) 3(1) 4(1)
2: 0(1) 5(1)
3: 1(1) 6(1)
4: 1(1) 7(1)
5: 2(1) 6(1)
6: 3(1) 5(1) 7(1)
7: 4(1) 6(1)
DFS Traversal: A B C F E D G H
```
其中,邻接矩阵中,INF表示两个结点之间没有边;邻接链表中,每个结点的后面跟着的数字是该结点与它相连的结点编号以及它们之间的边权;DFS遍历结果中,每个字母表示相应的结点被遍历到了。
阅读全文