用编程语言实现Kruskal算法和P算法求最小生成树(要写通用算法)
时间: 2024-10-19 14:12:36 浏览: 34
Kruskal算法和Prim算法都是用于寻找无向图中最小生成树的经典算法。以下是通用的Kruskal算法和Prim算法的Python实现:
**Kruskal算法 (适用于边集形式)**:
```python
def kruskal(graph):
edges = sorted(graph.items(), key=lambda x: x[1]) # 按权值升序排列边
mst = []
graph_set = set()
for edge in edges:
u, v, weight = edge
if u not in graph_set and v not in graph_set: # 避免形成环
graph_set.add(u)
graph_set.add(v)
mst.append(edge)
return mst
# 示例:
graph = {('A', 'B'): 4, ('A', 'D'): 8, ('B', 'C'): 5, ('C', 'D'): 9, ('D', 'E'): 7}
mst = kruskal(graph)
```
**Prim算法 (适用于邻接矩阵或邻接表)**
```python
import heapq
def prim(graph, start=None): # 如果未指定起始节点,默认选择任意节点
if start is None:
start, _ = min((node, weight) for node, weight in enumerate(graph[start] if isinstance(start, str) else graph))
visited = set()
unvisited = [(0, start)]
minheap = []
while unvisited:
current_weight, current_node = heapq.heappop(minheap)
if current_node in visited:
continue
visited.add(current_node)
for neighbor, weight in graph[current_node].items():
if neighbor not in visited:
heapq.heappush(minheap, (weight, neighbor))
return [edge for _, edge in visited.items()]
# 示例:
if isinstance(graph, dict): # 使用邻接字典表示邻接矩阵
matrix_graph = [[0 if 'A' not in node or 'B' not in node else weight for weight in row] for node, row in graph.items()]
else: # 使用邻接列表表示邻接表
matrix_graph = ... # 自行填充邻接表结构
mst = prim(matrix_graph, 'A')
```
阅读全文