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
66
67
68
69
70
71
72
73
|
type UnionFind struct {
parent []int
rank []int
}
func NewUnionFind(n int) *UnionFind {
uf := &UnionFind{parent: make([]int, n), rank: make([]int, n)}
for i := 0; i < n; i++ {
uf.parent[i] = i
uf.rank[i] = 1
}
return uf
}
func (uf *UnionFind) Find(i int) int {
if uf.parent[i] != i {
uf.parent[i] = uf.Find(uf.parent[i])
}
return uf.parent[i]
}
func (uf *UnionFind) Merge(i, j int) {
iF, jF := uf.Find(i), uf.Find(j)
if iF != jF {
if uf.rank[iF] <= uf.rank[jF] {
uf.parent[iF] = jF
} else {
uf.parent[jF] = iF
}
if uf.rank[iF] == uf.rank[jF] {
uf.rank[jF]++
}
}
}
func (uf *UnionFind) Count() int {
count := 0
for i := 0; i < len(uf.parent); i++ {
if uf.parent[i] == i {
count++
}
}
return count
}
func regionsBySlashes(grid []string) int {
n := len(grid)
size := 4 * n * n
uf := NewUnionFind(size)
for i := 0; i < n; i++ {
for j, ch := range grid[i] {
index := 4 * (i*n + j)
if ch == ' ' {
uf.Merge(index, index+1)
uf.Merge(index, index+2)
uf.Merge(index, index+3)
} else if ch == '/' {
uf.Merge(index, index+3)
uf.Merge(index+1, index+2)
} else if ch == '\\' {
uf.Merge(index, index+1)
uf.Merge(index+2, index+3)
}
if j+1 < n {
uf.Merge(index+1, 4*(i*n+j+1)+3)
}
if i+1 < n {
uf.Merge(index+2, 4*((i+1)*n+j))
}
}
}
return uf.Count()
}
|