编写一个程序用kruskal算法算出给定无向图的最小生成树
时间: 2023-09-04 18:07:16 浏览: 100
好的,以下是使用Kruskal算法求无向图的最小生成树的Python程序:
```python
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_mst(self):
result = []
i = 0
e = 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
print("Following are the edges in the constructed MST")
for u, v, weight in result:
print("{0} - {1}: {2}".format(u, v, weight))
g = Graph(5)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
g.kruskal_mst()
```
输出结果如下:
```
Following are the edges in the constructed MST
2 - 3: 4
0 - 3: 5
0 - 1: 10
```
这个程序实现了Kruskal算法,首先将所有边按照权重从小到大排序,然后逐个加入生成树中,如果加入这条边不会形成环路,那么就加入这条边。最终输出生成树的边以及对应的权重。
阅读全文