Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit df614e2

Browse files
committed
union find by rank
1 parent 6b62d70 commit df614e2

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
union_find.py
3+
An implementation of union find by rank data structure.
4+
Union Find Overview:
5+
------------------------
6+
A disjoint-set data structure, also called union-find data structure implements two functions:
7+
union(A, B) - merge A's set with B's set
8+
find(A) - finds what set A belongs to
9+
Union by rank approach:
10+
attach the smaller tree to the root of the larger tree
11+
Time Complexity : O(logn)
12+
Psuedo Code: http://en.wikipedia.org/wiki/Disjoint-set_data_structure
13+
"""
14+
class UnionFindByRank:
15+
def __init__(self, N):
16+
if type(N) != int:
17+
raise TypeError, "size must be integer"
18+
if N < 0:
19+
raise ValueError, "N cannot be a negative integer"
20+
self.parent = []
21+
self.rank = []
22+
self.N = N
23+
for i in range(0, N):
24+
self.parent.append(i)
25+
self.rank.append(0)
26+
27+
def make_set(self, x):
28+
if type(x) != int:
29+
raise TypeError, "x must be integer"
30+
if x != self.N:
31+
raise ValueError, "a new element must have index {0} since the total num of elements is {0}".format(self.N)
32+
self.parent.append(x)
33+
self.rank.append(0)
34+
self.N = self.N + 1
35+
36+
def union(self, x, y):
37+
self.__validate_ele(x)
38+
self.__validate_ele(y)
39+
x_root = self.find(x)
40+
y_root = self.find(y)
41+
if x_root == y_root:
42+
return
43+
# x and y are not already in same set. Merge them
44+
if self.rank[x_root] < self.rank[y_root]:
45+
self.parent[x_root] = y_root
46+
elif self.rank[x_root] > self.rank[y_root]:
47+
self.parent[y_root] = x_root
48+
else:
49+
self.parent[y_root] = x_root
50+
self.rank[x_root] = self.rank[x_root] + 1
51+
52+
def find(self, x):
53+
self.__validate_ele(x)
54+
if self.parent[x] == x:
55+
return x
56+
else:
57+
return self.find(self.parent[x])
58+
59+
def is_connected(self, x, y):
60+
self.__validate_ele(x)
61+
self.__validate_ele(y)
62+
return self.find(x) == self.find(y)
63+
64+
def __validate_ele(self, x):
65+
if type(x) != int:
66+
raise TypeError, "{0} is not an integer".format(x)
67+
if x < 0 or x >= self.N:
68+
raise ValueError, "{0} is not in [0,{1})".format(x, self.N)
69+

0 commit comments

Comments
 (0)