-
Notifications
You must be signed in to change notification settings - Fork 95
/
Kruskal.py
58 lines (50 loc) · 1.46 KB
/
Kruskal.py
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
class Graph:
def __init__(self, vertex):
self.V = vertex
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def search(self, parent, i):
if parent[i] == i:
return i
return self.search(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.search(parent, x)
yroot = self.search(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(self):
result = []
i, e = 0, 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.search(parent, u)
y = self.search(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("Edge:",u, v,end =" ")
print("-",weight)
g = Graph(5)
g.add_edge(0, 1, 8)
g.add_edge(0, 2, 5)
g.add_edge(1, 2, 9)
g.add_edge(1, 3, 11)
g.add_edge(2, 3, 15)
g.add_edge(2, 4, 10)
g.add_edge(3, 4, 7)
g.kruskal()