Prim算法生成最小代价生成树代码
时间: 2023-05-19 12:01:28 浏览: 99
prim算法生成最小代价生成树
以下是 Prim 算法生成最小代价生成树的代码:
```python
import heapq
def prim(graph, start):
visited = set()
heap = [(0, start)]
while heap:
(cost, node) = heapq.heappop(heap)
if node not in visited:
visited.add(node)
for neighbor, weight in graph[node].items():
if neighbor not in visited:
heapq.heappush(heap, (weight, neighbor))
return visited
```
其中,`graph` 是一个字典,表示图的邻接表,`start` 是起点。该算法返回一个集合,表示最小代价生成树的节点集合。
希望能帮到你!
阅读全文