Skip to content

Commit 1122d81

Browse files
committed
Add union
1 parent 9d829bb commit 1122d81

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

utils/union/union.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package union
2+
3+
type UnionFind struct {
4+
parent []int
5+
}
6+
7+
func NewUnionFind(size int) *UnionFind {
8+
uf := &UnionFind{
9+
parent: make([]int, size),
10+
}
11+
for i := range uf.parent {
12+
uf.parent[i] = i
13+
}
14+
return uf
15+
}
16+
17+
func (uf *UnionFind) Find(x int) int {
18+
if x == uf.parent[x] {
19+
return x
20+
}
21+
uf.parent[x] = uf.Find(uf.parent[x])
22+
return uf.parent[x]
23+
}
24+
25+
// Typically you'd also add Union:
26+
func (uf *UnionFind) Union(x, y int) {
27+
rootX := uf.Find(x)
28+
rootY := uf.Find(y)
29+
if rootX != rootY {
30+
uf.parent[rootX] = rootY
31+
}
32+
}

0 commit comments

Comments
 (0)