-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
50 lines (43 loc) · 775 Bytes
/
main.go
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
func findCircleNum(isConnected [][]int) int {
n := len(isConnected)
rank := make([]int, n)
group := make([]int, n)
for i := 0; i < n; i++ {
group[i] = i
}
var find func(int) int
find = func(u int) int {
if group[u] == u {
return u
}
group[u] = find(group[u])
return group[u]
}
unite := func(a, b int) {
ga := find(a)
gb := find(b)
if ga == gb {
return
}
if rank[ga] < rank[gb] {
group[ga] = gb
} else if rank[gb] < rank[ga] {
group[gb] = ga
} else { // equal
group[gb] = ga
rank[ga]++
}
}
for i, row := range isConnected {
for j, v := range row {
if v == 1 {
unite(i, j)
}
}
}
numGroups := map[int]struct{}{}
for i := 0; i < n; i++ {
numGroups[find(i)] = struct{}{}
}
return len(numGroups)
}