Skip to content

Instantly share code, notes, and snippets.

@okumin
Created September 15, 2012 13:30
Show Gist options
  • Save okumin/3727894 to your computer and use it in GitHub Desktop.
Save okumin/3727894 to your computer and use it in GitHub Desktop.
Union find
# -*- 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