python实现prim算法
时间: 2023-10-05 16:06:39 浏览: 74
prim算法 python 代码实现
Prim算法是一种求解最小生成树的贪心算法,以下是Python实现:
```python
def prim(graph):
# 初始化
visited = set()
unvisited = set(graph.keys())
start = unvisited.pop()
visited.add(start)
edges = [(weight, start, neighbor) for neighbor, weight in graph[start].items()]
# 开始贪心
while unvisited:
# 选择最小边
weight, frm, to = min(edges)
edges.remove((weight, frm, to))
# 如果终点未被访问过,则加入最小生成树
if to in unvisited:
unvisited.remove(to)
visited.add(to)
yield frm, to, weight
# 更新可选边
for neighbor, weight in graph[to].items():
if neighbor in unvisited:
edges.append((weight, to, neighbor))
```
这个函数接受一个字典作为参数,字典的键是节点,值是另一个字典,它的键是相邻节点,值是权重。函数返回一个生成器,每次迭代返回一个三元组,表示加入最小生成树的一条边和它的权重。
阅读全文