Created
September 15, 2012 13:30
-
-
Save okumin/3727894 to your computer and use it in GitHub Desktop.
Union find
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
class UnionFind: | |
def __init__(self): | |
self.refs = {} | |
def find(self, x): | |
if x in self.refs: | |
ref = self.find(self.refs[x]) | |
self.refs[x] = ref | |
return ref | |
else: | |
return x | |
def unify(self, x, y): | |
X = self.find(x) | |
Y = self.find(y) | |
if X == Y: | |
return | |
else: | |
self.refs[X] = Y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment