Union find is a algorithm that widly used in check connectivity in a graph.
Imagine connecting node as tree. Need to balance it while union and find, or else the time complexity for traversal would be O(N) instead of the height of the tree.
classUF: def__init__(self, n=0): # n disconnected node # number of tree self.count = n
# the parent of each node self.parent = {}
# size of each tree self.size = {}
for i inrange(n): self.parent[i] = i self.size[i] = 1
defunion(self, p, q): """ connect p and q Parameter: p: int q: int """ rootP = self.find(p) rootQ = self.find(q) if rootP == rootQ: return
# for balance purpose # append the smaller party to the larger party if self.size[rootP] > self.size[rootQ]: self.parent[rootQ] = rootP self.size[rootP] += self.size[rootQ] else: self.parent[rootP] = rootQ self.size[rootQ] += self.size[rootQ] self.count -= 1
defconnected(self, p, q): """ check connectivity between p and q """ return self.find(p) == self.find(q)
deffind(self, x): """ find the root of x """ while self.parent[x] != x:
# balance the tree while finding self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x