Skip to content

Commit 73cba74

Browse files
authored
Add union-find example (#196)
1 parent fd5044c commit 73cba74

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

‎src/algorithm_theory/union_find.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class UnionFind:
2+
def __init__(self):
3+
self.roots = []
4+
5+
def add_edges(self, n: int, edges: list[tuple[int, int]]):
6+
self.roots = [number for number in range(n)]
7+
for edge in edges:
8+
a, b = edge
9+
self.union(a, b)
10+
11+
def components(self) -> int:
12+
count = 0
13+
14+
for index in range(len(self.roots)):
15+
if self.roots[index] == index:
16+
count += 1
17+
18+
return count
19+
20+
def union(self, a: int, b: int):
21+
root_a = self.find(a)
22+
root_b = self.find(b)
23+
24+
if root_a is not None and root_b is not None:
25+
self.roots[root_a] = root_b
26+
27+
def find(self, node1: int) -> None | int:
28+
stack = [node1]
29+
30+
while stack:
31+
current = stack.pop()
32+
if self.roots[current] == current:
33+
return current
34+
stack.append(self.roots[current])
35+
return None
36+
37+
def size(self) -> int:
38+
return len(self.roots)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from src.algorithm_theory.union_find import UnionFind
2+
3+
4+
def test_initializer():
5+
union_find = UnionFind()
6+
assert union_find.size() == 0
7+
assert union_find.components() == 0
8+
9+
10+
def test_components():
11+
union_find = UnionFind()
12+
union_find.add_edges(7, [(0, 2), (1, 0), (4, 3), (2, 5), (3, 6)])
13+
14+
assert union_find.components() == 2

0 commit comments

Comments
 (0)