用python写一个 Prim算法代码(必须有每行注释)
时间: 2024-11-15 21:25:22 浏览: 4
基于Python实现的数据结构与算法完整源代码+超详细注释(包含46个作业项目).zip
```python
# Prim's Algorithm in Python for finding minimum spanning tree (MST)
import sys
def prim(graph, start):
# 初始化:标记所有边为未访问,创建空集合用于存放已选择的最小权重边,以及一个字典保存每个顶点的最短路径起点
visited = [False] * len(graph)
edges = []
parent = [-1] * len(graph)
# 将起始顶点的距离设置为0,并加入已访问集合
distance[start] = 0
visited[start] = True
while edges != len(graph) - 1: # 边的数量还没达到n-1,因为MST需要n-1条边
min_distance = float('inf') # 初始化最小距离为无穷大
u = -1 # 存储当前最小边的起点
# 遍历所有未访问的顶点,找到到它们的最小边
for v in range(len(graph)):
if visited[v] == False and graph[start][v] != 0 and graph[start][v] < min_distance:
min_distance = graph[start][v]
u = v
# 更新节点信息,将找到的最小边加入edges,并将其终点添加为已访问
visited[u] = True
edges.append((start, u)) # 添加起点u到之前的起点(start)
parent[u] = start # 设置parent[u]为起点
start = u # 将搜索焦点转移到下一个未访问的起点u
return edges, parent
# 示例图的邻接矩阵表示,其中0表示不存在边,正数表示权重
graph = [
[0, 2, 0, 6],
[2, 0, 3, 8],
[0, 3, 0, 5],
[6, 8, 5, 0]
]
# 使用Prim算法从第一个节点开始找MST
result_edges, _ = prim(graph, 0)
print("Minimum Spanning Tree Edges (from node 0):")
for edge in result_edges:
print(f"Edge from {edge[0]} to {edge[1]} with weight {graph[edge[0]][edge[1]]}")
阅读全文