-
Notifications
You must be signed in to change notification settings - Fork 13
/
disjointSet.py
31 lines (27 loc) · 857 Bytes
/
disjointSet.py
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
class DisjointSet:
def __init__(self, vertices):
self.vertices = vertices
self.parent = {}
for v in vertices:
self.parent[v] = v
self.rank = dict.fromkeys(vertices, 0)
def find(self, item):
if self.parent[item] == item:
return item
else:
return self.find(self.parent[item])
def union(self, x, y):
xroot = self.find(x)
yroot = self.find(y)
if self.rank[xroot] < self.rank[yroot]:
self.parent[xroot] = yroot
elif self.rank[xroot] > self.rank[yroot]:
self.parent[yroot] = xroot
else:
self.parent[yroot] = xroot
self.rank[xroot] += 1
# vertices = ["A", "B", "C", "D", "E"]
# ds = DisjointSet(vertices)
# ds.union("A", "B")
# ds.union("A", "C")
# print(ds.find("A")