1. 先依次输入无向图的顶点信息,再依次输入无向图的边信息,建立图的邻接矩阵存储结构并将其顶点向量和邻接矩阵打印输出:
时间: 2024-02-06 17:10:54 浏览: 74
好的,以下是 Python 代码实现:
```python
# 定义图的邻接矩阵存储类
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adj_matrix = [[0] * len(vertices) for i in range(len(vertices))]
# 添加边
def add_edge(self, v1, v2):
index1 = self.vertices.index(v1)
index2 = self.vertices.index(v2)
self.adj_matrix[index1][index2] = 1
self.adj_matrix[index2][index1] = 1
# 打印邻接矩阵
def print_adj_matrix(self):
print("邻接矩阵:")
print(" ", end="")
for vertex in self.vertices:
print(vertex, end=" ")
print()
for i in range(len(self.adj_matrix)):
print(self.vertices[i], end=" ")
for j in range(len(self.adj_matrix[i])):
print(self.adj_matrix[i][j], end=" ")
print()
# 主程序
if __name__ == '__main__':
# 输入顶点信息
vertices = input("请输入无向图的顶点信息(以空格分隔):").split()
# 创建邻接矩阵存储的图
graph = Graph(vertices)
# 输入边信息
print("请输入无向图的边信息(每行两个顶点,以空格分隔):")
while True:
edge = input().split()
if len(edge) != 2:
break
graph.add_edge(edge[0], edge[1])
# 打印邻接矩阵
graph.print_adj_matrix()
```
运行示例:
```
请输入无向图的顶点信息(以空格分隔):A B C D E F
请输入无向图的边信息(每行两个顶点,以空格分隔):
A B
B C
C D
D E
E F
A F
邻接矩阵:
A B C D E F
A 0 1 0 0 0 1
B 1 0 1 0 0 0
C 0 1 0 1 0 0
D 0 0 1 0 1 0
E 0 0 0 1 0 1
F 1 0 0 0 1 0
```
阅读全文