用代码生成实现图的邻接矩阵和邻接表的存储。 (1)建立图1的邻接表存储结构并输出; (2)建立图1的邻接矩阵存储结构并输出。
时间: 2024-02-03 18:15:10 浏览: 74
以下是 Python 代码实现:
```python
# 定义图的邻接矩阵存储结构
class AdjMatrixGraph:
def __init__(self, vertex_num, edges):
self.vertex_num = vertex_num
self.edges = edges
self.matrix = [[0] * vertex_num for _ in range(vertex_num)]
for edge in edges:
self.matrix[edge[0]-1][edge[1]-1] = 1
self.matrix[edge[1]-1][edge[0]-1] = 1
def __str__(self):
output = ''
for row in self.matrix:
output += ' '.join([str(val) for val in row]) + '\n'
return output
# 定义图的邻接表存储结构
class AdjListGraph:
def __init__(self, vertex_num, edges):
self.vertex_num = vertex_num
self.edges = edges
self.adj_list = [[] for _ in range(vertex_num)]
for edge in edges:
self.adj_list[edge[0]-1].append(edge[1])
self.adj_list[edge[1]-1].append(edge[0])
def __str__(self):
output = ''
for i in range(self.vertex_num):
output += str(i+1) + ': '
output += ' '.join([str(val) for val in self.adj_list[i]]) + '\n'
return output
# 测试数据
vertex_num = 7
edges = [(1,2),(1,4),(2,3),(2,5),(3,6),(4,5),(5,6),(5,7),(6,7)]
# 建立图的邻接表存储结构并输出
graph_list = AdjListGraph(vertex_num, edges)
print(graph_list)
# 建立图的邻接矩阵存储结构并输出
graph_matrix = AdjMatrixGraph(vertex_num, edges)
print(graph_matrix)
```
输出结果如下:
```
1: 2 4
2: 1 3 5
3: 2 6
4: 1 5
5: 2 4 6 7
6: 3 5 7
7: 5 6
0 1 0 1 0 0 0
1 0 1 0 1 0 0
0 1 0 0 0 1 0
1 0 0 0 1 0 0
0 1 0 1 0 1 1
0 0 1 0 1 0 1
0 0 0 0 1 1 0
```
阅读全文