Skip to content

Commit 9a8a2c7

Browse files
author
Hamid Gasmi
committed
#296: implement kruskal's algorithm
1 parent eebc079 commit 9a8a2c7

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution:
2+
def minimumCost(self, n: int, connections: List[List[int]]) -> int:
3+
minimum_edges_count = n - 1
4+
if len(connections) < minimum_edges_count:
5+
return - 1
6+
7+
connections.sort(key=lambda edge:edge[2])
8+
9+
union_find = Union_Find_Path_Compression_Heuristic(n)
10+
11+
path_total_cost = 0
12+
mst_edges_count = 0
13+
for [ a, b, cost ] in connections:
14+
node_a = a - 1
15+
node_b = b - 1
16+
17+
if union_find.find(node_a) == union_find.find(node_b):
18+
continue
19+
20+
mst_edges_count += 1
21+
path_total_cost += cost
22+
union_find.union(node_a, node_b)
23+
24+
return path_total_cost if mst_edges_count == minimum_edges_count else -1
25+
26+
class Union_Find_Path_Compression_Heuristic:
27+
def __init__(self, n: int):
28+
self.__rank = [ 0 for _ in range(n) ]
29+
self.__parent = [ i for i in range(n) ]
30+
31+
# Time Complexity: O(logn)
32+
def find(self, i: int) -> int:
33+
if i < 0 or i >= len(self.__parent):
34+
return -1
35+
36+
if i != self.__parent[i]:
37+
self.__parent[i] = self.find(self.__parent[i])
38+
39+
return self.__parent[i]
40+
41+
# Time Complexity: O(logn)
42+
def union(self, i: int, j: int):
43+
root_i = self.find(i)
44+
root_j = self.find(j)
45+
if root_i == root_j:
46+
return
47+
48+
if self.__rank[root_i] > self.__rank[root_j]:
49+
# We choose root_i as the root of the merged tree
50+
self.__parent[root_j] = root_i
51+
52+
else:
53+
# We choose root_j as the root of the merged tree
54+
self.__parent[root_i] = root_j
55+
if self.__rank[root_i] == self.__rank[root_j]:
56+
self.__rank[root_j] += 1
57+

0 commit comments

Comments
 (0)