Skip to content

Commit

Permalink
Implemented disjoint set
Browse files Browse the repository at this point in the history
  • Loading branch information
prawn-cake committed Feb 10, 2018
1 parent 9d03550 commit 85168d6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ my implementation is a good start to customize it for your needs.
* bfs
* [BK-Tree](https://en.wikipedia.org/wiki/BK-tree)
* [Prefix tree](https://en.wikipedia.org/wiki/Trie)
* [Disjoint set](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)

## Links

Expand Down
37 changes: 37 additions & 0 deletions structures/disjoint_set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-


class DSet(object):
"""Disjoint set using union quick find implementation"""

def __init__(self, data, getter=lambda p: p):
self._map = {getter(item): i for i, item in enumerate(data)}
self._index = list(range(len(data)))
self._getter = getter

def union(self, p, q):
"""Union of two elements
"""
p_idx = self._map[self._getter(p)]
q_idx = self._map[self._getter(q)]

# Update all previous elements to the new root
tmp_value = self._index[p_idx]
for i in range(len(self._index)):
if self._index[i] == tmp_value:
self._index[i] = self._index[q_idx]

def connected(self, p, q):
p_val, q_val = map(self._getter, [p, q])
return self._index[self._map[p_val]] == self._index[self._map[q_val]]


if __name__ == '__main__':
dset = DSet(['A', 'B', 'C', 'D', 'E'])
dset.union('A', 'B')
dset.union('B', 'E')
dset.union('E', 'D')

assert dset.connected('A', 'E') is True
assert dset.connected('D', 'C') is False

0 comments on commit 85168d6

Please sign in to comment.