-
Notifications
You must be signed in to change notification settings - Fork 51
/
Kruskal's Algorithm.py
58 lines (51 loc) · 1.53 KB
/
Kruskal's Algorithm.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=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.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)
print("\nEdge\t Weight \n")
for u, v, weight in result:
print(u, "-", v, "\t ", weight)
g = Graph(5)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(1, 2, 5)
g.add_edge(1, 3, 16)
g.add_edge(2, 3, 22)
g.add_edge(2, 4, 4)
g.add_edge(3, 4, 8)
g.kruskal()