python 实现将带权图的领接矩阵转换成邻接表,和将邻接表转换成邻接矩阵 及测试用例
时间: 2023-10-06 11:06:44 浏览: 93
图的邻接矩阵和邻接表实现
以下是将带权图的领接矩阵转换成邻接表的 Python 代码和测试用例:
```python
def matrix_to_list(matrix):
n = len(matrix)
graph = {}
for i in range(n):
for j in range(n):
if matrix[i][j] != 0:
if i not in graph:
graph[i] = []
graph[i].append((j, matrix[i][j]))
return graph
# 测试用例
matrix = [
[0, 2, 3, 0],
[2, 0, 4, 1],
[3, 4, 0, 5],
[0, 1, 5, 0]
]
graph = matrix_to_list(matrix)
print(graph) # 输出:{0: [(1, 2), (2, 3)], 1: [(0, 2), (2, 4), (3, 1)], 2: [(0, 3), (1, 4), (3, 5)], 3: [(1, 1), (2, 5)]}
```
以下是将邻接表转换成邻接矩阵的 Python 代码和测试用例:
```python
def list_to_matrix(graph, directed=False):
n = len(graph)
matrix = [[0] * n for _ in range(n)]
for node in graph:
for neighbor, weight in graph[node]:
matrix[node][neighbor] = weight
if not directed:
matrix[neighbor][node] = weight
return matrix
# 测试用例
graph = {
0: [(1, 2), (2, 3)],
1: [(0, 2), (2, 4), (3, 1)],
2: [(0, 3), (1, 4), (3, 5)],
3: [(1, 1), (2, 5)]
}
matrix = list_to_matrix(graph)
print(matrix) # 输出:[[0, 2, 3, 0], [2, 0, 4, 1], [3, 4, 0, 5], [0, 1, 5, 0]]
```
注意,测试用例中的带权图是一个无向图,如果是有向图需要将 `directed` 参数设置为 `True`。
阅读全文