Skip to content

Commit ac5f5a1

Browse files
committed
readded rank/pointers union-find
1 parent 618cffe commit ac5f5a1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package structures
2+
3+
import "fmt"
4+
5+
type UnionFindSet struct {
6+
parent *UnionFindSet
7+
rank int
8+
value int
9+
}
10+
11+
func NewUnionFindSet(value int) *UnionFindSet {
12+
uf := UnionFindSet{nil, 0, value}
13+
uf.parent = &uf
14+
return &uf
15+
}
16+
17+
func (uf *UnionFindSet) Find() *UnionFindSet {
18+
if uf.parent == uf {
19+
return uf
20+
}
21+
return uf.parent.Find()
22+
23+
}
24+
25+
func (uf *UnionFindSet) Union(other *UnionFindSet) *UnionFindSet {
26+
ufParent := uf.Find()
27+
otherParent := other.Find()
28+
if ufParent == otherParent {
29+
return ufParent
30+
}
31+
if otherParent.rank > ufParent.rank {
32+
ufParent.parent = otherParent
33+
return otherParent
34+
} else {
35+
otherParent.parent = ufParent
36+
if otherParent.rank == ufParent.rank {
37+
ufParent.rank++
38+
}
39+
return ufParent
40+
}
41+
42+
}
43+
44+
func (uf *UnionFindSet) String() string {
45+
if uf.parent == uf {
46+
return fmt.Sprintf("[%v]: %v", uf.rank, uf.value)
47+
}
48+
str := fmt.Sprintf("[%v]: %v -> %v", uf.rank, uf.value, uf.parent)
49+
return str
50+
}

0 commit comments

Comments
 (0)