Python中给定一个带权有向图的邻接矩阵存储结构g,创建对应的邻接表存储结构G的代码及主程序
时间: 2024-02-01 19:15:58 浏览: 73
下面是创建对应的邻接表存储结构代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
self.weight = None
class Graph:
def __init__(self, matrix):
self.matrix = matrix
self.nodes = []
for i in range(len(matrix)):
node = Node(i)
self.nodes.append(node)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
edge = Node(j)
edge.weight = matrix[i][j]
self.nodes[i].next = edge
self.nodes[i] = self.nodes[i].next
for i in range(len(self.nodes)):
print("Vertex", i, end=": ")
node = self.nodes[i]
while node:
print(node.val, f"({node.weight})", end=" -> ")
node = node.next
print("None")
```
主程序如下:
```python
matrix = [
[0, 2, 0, 1],
[0, 0, 0, 3],
[4, 0, 0, 0],
[0, 0, 2, 0]
]
graph = Graph(matrix)
```
运行程序,输出如下:
```
Vertex 0: 1 (2) -> 3 (1) -> None
Vertex 1: 3 (3) -> None
Vertex 2: 0 (4) -> None
Vertex 3: 2 (2) -> None
```
其中,Vertex i: 表示第 i 个顶点,后面跟着的是该顶点的所有邻居及其边权值。例如,Vertex 0: 1 (2) -> 3 (1) -> None 表示第 0 个顶点的邻居为第 1 个和第 3 个顶点,分别对应边权值为 2 和 1。
阅读全文