-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal_algorithm.py
More file actions
59 lines (49 loc) · 1.28 KB
/
kruskal_algorithm.py
File metadata and controls
59 lines (49 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import graph
from collections import defaultdict
def find_parent(parent, vertex):
if parent[vertex] == vertex:
return vertex
else:
return find_parent(parent, parent[vertex])
def union(parent,rank,x,y):
xroot = find_parent(parent, x)
yroot = find_parent(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(g):
# Sort all edges
result = []
V = len(g)
rank = {}
parent = {}
edge_list = []
# This creates a list of edges with source and destination sorted by edge weight
for i in g:
edges = g[i]
for e in edges:
edge_list.append((i,e[0],e[1]))
edge_list = sorted(edge_list, key = lambda x:x[2])
for vertex in g:
parent[vertex] = vertex
rank[vertex] = 0
e = 0
i = 0
while e < V-1:
s,d,w = edge_list[i]
i += 1
x = find_parent(parent,s)
y = find_parent(parent,d)
if x != y:
e += 1
result.append((s,d,w))
union(parent,rank,x,y)
print(result)
def test():
g = graph.createTestGraph()
kruskal_mst(g._graph)
# print(g)