最小生成树python
时间: 2023-08-27 19:16:03 浏览: 87
最小生成树有很多种生成方法,主要有普利姆算法和克鲁斯卡尔算法
在Python中,可以使用Prim算法或Kruskal算法来实现最小生成树。下面是一个使用Prim算法的示例代码:
```python
import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)]
def min_key(self, key, mst_set):
min_val = sys.maxsize
min_index = -1
for v in range(self.V):
if key[v] < min_val and mst_set[v] == False:
min_val = key[v]
min_index = v
return min_index
def prim_mst(self):
key = [sys.maxsize] * self.V
parent = [None] * self.V
key[0] = 0
mst_set = [False] * self.V
parent[0] = -1
for _ in range(self.V):
u = self.min_key(key, mst_set)
mst_set[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mst_set[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
return parent
def print_mst(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
# 测试代码
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
parent = g.prim_mst()
g.print_mst(parent)
```
这段代码使用了邻接矩阵来表示图,并实现了Prim算法来找到最小生成树。你可以根据自己的需求调整图的表示方式和权值。
阅读全文