利用 Prim 算法求解最小生成树问题,用Python语言描述算法。
时间: 2024-09-30 09:15:32 浏览: 32
Prim算法与Kruskal算法求最小生成树
4星 · 用户满意度95%
Prim算法是一种用于寻找图中连通分量中最短路径的贪心算法,特别适用于求解带权无向图的最小生成树问题。以下是Prim算法的一个基本Python实现:
```python
import heapq
class Node:
def __init__(self, index, weight=None):
self.index = index
self.weight = weight if weight is not None else 0
def prim(graph, start_node):
# 初始化集合和堆
visited = set()
unvisited_nodes = [(node.weight, node) for node in graph]
heapq.heapify(unvisited_nodes)
# 创建最小生成树
mst = []
while unvisited_nodes:
current_weight, current_node = heapq.heappop(unvisited_nodes)
# 如果当前节点已访问,则跳过
if current_node.index in visited:
continue
# 将当前节点添加到已访问集合,并加入最小生成树
visited.add(current_node.index)
mst.append((current_node.index, current_node.weight))
# 更新未访问节点集,考虑所有与当前节点相连且尚未访问的节点
for neighbor, weight in graph[current_node.index].items():
if neighbor not in visited:
heapq.heappush(unvisited_nodes, (weight, Node(neighbor, weight)))
return mst
# 示例:一个邻接字典表示的图,键是节点,值是字典,键是邻居节点,值是边的权重
graph = {
'A': {'B': 5, 'D': 1},
'B': {'A': 5, 'C': 2},
'C': {'B': 2, 'E': 4},
'D': {'A': 1, 'E': 8},
'E': {'C': 4, 'D': 8}
}
start_node = 'A'
min_spanning_tree = prim(graph, start_node)
print(f"最小生成树:{min_spanning_tree}")
阅读全文