写一个prim算法的示例代码
时间: 2023-11-04 10:07:23 浏览: 77
Prim算法构造最小生成树
5星 · 资源好评率100%
以下是一个基于Python的Prim算法示例代码:
```python
# Prim算法示例代码
def prim(graph):
"""
Prim算法实现
:param graph: 图,使用邻接矩阵表示
:return: 最小生成树的权值和
"""
n = len(graph)
visited = [False] * n # 记录节点是否被访问过
dist = [float('inf')] * n # 记录每个节点到最小生成树的最短距离
dist[0] = 0 # 从第一个节点开始构建最小生成树
for _ in range(n):
u = -1 # u记录当前未访问的节点中距离最小的节点
for i in range(n):
if not visited[i] and (u == -1 or dist[i] < dist[u]):
u = i
visited[u] = True # 将u标记为已访问
for v, w in graph[u]:
if not visited[v] and w < dist[v]:
dist[v] = w
return sum(dist)
# 示例
graph = [
[(1, 7), (2, 9), (5, 14)],
[(0, 7), (2, 10), (3, 15)],
[(0, 9), (1, 10), (3, 11), (5, 2)],
[(1, 15), (2, 11), (4, 6)],
[(3, 6), (5, 9)],
[(0, 14), (2, 2), (4, 9)]
]
print(prim(graph)) # 输出:37
```
阅读全文