Skip to content

Commit c010ba0

Browse files
committed
feat: add kruskals algorithm for minimum spanning tree
1 parent 7fbbb09 commit c010ba0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution:
2+
class DSU:
3+
def __init__(self, n: int):
4+
self.parents = list(range(n))
5+
self.ranks = [0] * n
6+
7+
def find(self, u: int) -> int:
8+
if u == self.parents[u]:
9+
return u
10+
11+
self.parents[u] = self.find(self.parents[u])
12+
return self.parents[u]
13+
14+
def union(self, u: int, v: int):
15+
pU, pV = self.find(u), self.find(v)
16+
17+
if pU == pV:
18+
return
19+
20+
if self.ranks[pU] < self.ranks[pV]:
21+
self.parents[pU] = pV
22+
elif self.ranks[pV] < self.ranks[pU]:
23+
self.parents[pV] = pU
24+
else:
25+
self.parents[pU] = pV
26+
self.ranks[pV] += 1
27+
28+
def spanningTree(self, V: int, edges: list[list[int]]) -> int:
29+
dsu = self.DSU(V)
30+
31+
# sort by weights in ascending order
32+
edges.sort(key=lambda x: x[2])
33+
mst = 0
34+
35+
for u, v, weight in edges:
36+
# if both are in different components union them
37+
if dsu.find(u) != dsu.find(v):
38+
dsu.union(u, v)
39+
mst += weight
40+
41+
return mst

0 commit comments

Comments
 (0)