-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathUnionFind.py
More file actions
47 lines (38 loc) · 1.31 KB
/
UnionFind.py
File metadata and controls
47 lines (38 loc) · 1.31 KB
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
# Implementation of Union Find / Disjoint Set Union (DSU) in python
# DSU object will be instantiated and called as such:
# obj = UnionFind(n)
# obj.unite(x, y)
# parent = obj.findRootOf(x)
# connected = obj.isConnected(x, y)
class UnionFind:
def __init__(self, n):
''' Create n sets '''
self.root = [i for i in range(n)]
self.rank = [1] * n
self.sets = n
def findRootOf(self, x):
''' Find the root of x '''
while self.root[x] != x:
# Path compression
self.root[x] = self.root[self.root[x]]
x = self.root[x]
return x
def unite(self, x, y):
''' Unite the sets of x and y '''
rootX = self.findRootOf(x)
rootY = self.findRootOf(y)
# Return if they belong from the same sets
if rootX == rootY:
return
# Put the smaller set into the bigger set
if self.rank[rootY] > self.rank[rootX]:
self.root[rootX] = rootY
self.rank[rootY] += self.rank[rootX]
else:
self.root[rootY] = rootX
self.rank[rootX] += self.rank[rootY]
# Decrement set count
self.sets -= 1
def isConnected(self, x, y):
''' Check if x and y belong to the same set '''
return self.findRootOf(x) == self.findRootOf(y)