Skip to content

Instantly share code, notes, and snippets.

@cocodrips
Last active January 25, 2018 16:50
Show Gist options
  • Save cocodrips/35f83d9524ee6f618e73 to your computer and use it in GitHub Desktop.
Save cocodrips/35f83d9524ee6f618e73 to your computer and use it in GitHub Desktop.
Union Find in Python
class UnionFind:
def __init__(self, n):
self.par = range(n)
self.rank = [0 for i in xrange(n)]
def find(self, x):
if self.par[x] == x:
return x
self.par[x] = self.find(self.par[x])
return self.par[x]
def same(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment