-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionFind.go
More file actions
65 lines (50 loc) · 994 Bytes
/
unionFind.go
File metadata and controls
65 lines (50 loc) · 994 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"fmt"
)
//Node have rank for tree height and key for its name
type Node struct {
key int
parent pNode
rank int
}
type pNode *Node
func find(x pNode) pNode {
for x != x.parent {
x = find(x.parent)
}
return x
}
func union(a pNode, b pNode) {
rootA := find(a)
rootB := find(b)
if rootA == rootB {
fmt.Printf("%d and %d are connected!\n", a.key, b.key)
return
}
if rootA.rank > rootB.rank {
rootB.parent = rootA
fmt.Printf("%d is linking to %d\n", b.key, a.key)
} else {
rootA.parent = rootB
if rootA.rank == rootB.rank {
rootB.rank++
}
fmt.Printf("%d is linking to %d\n", a.key, b.key)
}
}
func main() {
tree := make([]Node, 10)
for i := range tree {
tree[i] = Node{key: i, rank: 0}
tree[i].parent = &tree[i]
}
fmt.Println(tree)
union(&tree[1], &tree[2])
union(&tree[0], &tree[3])
union(&tree[2], &tree[9])
union(&tree[7], &tree[9])
union(&tree[9], &tree[3])
fmt.Println(tree)
fmt.Println(15/10, 15%10)
}