-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find_recursive.py
More file actions
40 lines (29 loc) · 861 Bytes
/
union_find_recursive.py
File metadata and controls
40 lines (29 loc) · 861 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
34
35
36
37
38
39
40
'''
UnionFind is a disojoint data structure which supports:
O(lg*N) find
O(lg*N) union
very useful in graph, tree, and other set-union algorithms
This implementation use recursion for the find method
Created on April 24th, 2022
@author: tonytan4ever
'''
class UnionFind:
def __init__(self):
self.parents = {}
# (TODO): Add union find customized logics here
def find(self, x, path_compression=True):
p = self.parents[x]
if x != p:
pp = self.find(p)
self.parents[x] = pp
return self.parents[x]
def union(self, a, b):
root_a, root_b = self.find(a), self.find(b)
if root_a != root_b:
self.parents[root_a] = root_b
return True
else:
return False
if __name__ == '__main__':
# (TODO): Add more tests here...
pass