Skip to content

Instantly share code, notes, and snippets.

View wcchin's full-sized avatar

Benny Chin wcchin

View GitHub Profile
@artkpv
artkpv / union_find.py
Last active February 15, 2021 12:03
Union-Find in Python (weighted, path compression, connected components)
class UnionFind:
"""Weighted quick-union with path compression and connected components.
The original Java implementation is introduced at
https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf
>>> uf = UnionFind(10)
>>> for (p, q) in [(3, 4), (4, 9), (8, 0), (2, 3), (5, 6), (5, 9),
... (7, 3), (4, 8), (6, 1)]:
... uf.union(p, q)