Skip to content

Instantly share code, notes, and snippets.

@horiajurcut
Created September 1, 2014 23:21
Show Gist options
  • Save horiajurcut/acd701348002d8077f4a to your computer and use it in GitHub Desktop.
Save horiajurcut/acd701348002d8077f4a to your computer and use it in GitHub Desktop.
class QuickFindUF:
def __init__(self, n):
self.id = []
for i in range(0, n):
self.id.append(i)
def connected(self, p, q):
return self.id[p] == self.id[q]
def union(self, p, q):
pid = self.id[p]
qid = self.id[q]
for idx, val in enumerate(self.id):
if val == pid:
self.id[idx] = qid
if __name__ == '__main__':
uf = QuickFindUF(10)
uf.union(1, 2)
uf.union(4, 3)
uf.union(3, 4)
uf.union(1, 3)
print uf.connected(2, 3)
print uf.id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment