forked from orphu/mcdungeon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
disjoint_set.py
56 lines (42 loc) · 1.22 KB
/
disjoint_set.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# A simple disjoint set ADT which uses path compression on finds
# to speed things up
#
# Borrowed from:
# http://pixelenvy.ca/wa/ca_cave.html
class DisjointSet:
size = 0
def __init__(self):
self.__items = {}
def union(self, root1, root2):
if self.__items[root2] < self.__items[root1]:
self.__items[root1] = root2
else:
if self.__items[root1] == self.__items[root2]:
self.__items[root1] -= 1
self.__items[root2] = root1
def find(self, x):
try:
while self.__items[x] > 0:
x = self.__items[x]
except KeyError:
self.__items[x] = -1
return x
def split_sets(self):
sets = {}
j = 0
for j in self.__items.keys():
root = self.find(j)
if root > 0:
if root in sets:
list = sets[root]
list.append(j)
sets[root] = list
else:
sets[root] = [j]
return sets
def dump(self):
sets = self.split_sets()
for k, v in sets.items():
print k
for l in v:
print '\t', l