-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisjoint_set.py
More file actions
33 lines (29 loc) · 959 Bytes
/
disjoint_set.py
File metadata and controls
33 lines (29 loc) · 959 Bytes
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
class DisjointSet:
def __init__(self, size):
self.rank = [1]*size
self.root = [i for i in range(size)]
# path compression
def find(self, x):
# found final parent
if x == self.root[x]:
return x
# recursive call to find parent of index x
self.root[x] = self.find(self.root[x])
# return values
return self.root[x]
# union by rank
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
# cycle detected
if rootX==rootY:
return True
else:
if self.rank[rootX] < self.rank[rootY]:
self.root[rootX] = self.root[rootY]
elif self.rank[rootX] > self.rank[rootY]:
self.root[rootY] = self.root[rootX]
else:
self.rank[rootX] += 1
self.root[rootY] = self.root[rootX]
return False