-
Notifications
You must be signed in to change notification settings - Fork 14
/
Kruskal.py
59 lines (49 loc) · 1.25 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
import DisjointSet as dst
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
self.nodes = []
self.MST = []
def addEdge(self,s,d,w):
self.graph.append([s,d,w])
def addNode(self,val):
self.nodes.append(val)
def printSol(self, s,d,w):
for s,d,w in self.MST:
print("%s - %s : %s" % (s,d,w))
def kruskalAlgo(self):
i,e = 0 ,0
ds = dst.DisjointSet(self.nodes)
self.graph = sorted(self.graph, key = lambda item : item[2])
while e < self.V - 1:
s, d, w = self.graph[i]
i += 1
x = ds.find(s)
y = ds.find(d)
if x != y:
e += 1
self.MST.append([s,d,w])
ds.union(x,y)
self.printSol(s,d,w)
g = Graph(5)
g.addNode("A")
g.addNode("B")
g.addNode("C")
g.addNode("D")
g.addNode("E")
g.addEdge("A", "B", 5)
g.addEdge("A", "C", 13)
g.addEdge("A", "E", 15)
g.addEdge("B", "A", 5)
g.addEdge("B", "C", 10)
g.addEdge("B", "D", 8)
g.addEdge("C", "A", 13)
g.addEdge("C", "B", 10)
g.addEdge("C", "E", 20)
g.addEdge("C", "D", 6)
g.addEdge("D", "B", 8)
g.addEdge("D", "C", 6)
g.addEdge("E", "A", 15)
g.addEdge("E", "C", 20)
g.kruskalAlgo()