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
74
75
| // @Title: 由斜杠划分区域 (Regions Cut By Slashes)
// @Author: 15816537946@163.com
// @Date: 2021-01-25 23:02:02
// @Runtime: 0 ms
// @Memory: 4.6 MB
type unionFind struct {
parent, size []int
setCount int // 当前连通分量
}
func newUnionFind(n int) *unionFind {
parent := make([]int, n)
size := make([]int, n)
for i := range parent {
parent[i] = i
size[i] = 1
}
return &unionFind{parent, size, n}
}
// 路径压缩
func (uf *unionFind) find(x int) int {
if uf.parent[x] != x {
uf.parent[x] = uf.find(uf.parent[x])
}
return uf.parent[x]
}
func (uf *unionFind) union(x, y int) {
fx, fy := uf.find(x), uf.find(y)
if fx == fy {
return
}
if uf.size[fx] < uf.size[fy] {
fx, fy = fy, fx
}
uf.parent[fy] = fx
uf.size[fx] += uf.size[fy]
uf.setCount--
}
func regionsBySlashes(grid []string) int {
n := len(grid)
uf := newUnionFind(4 * n * n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
idx := i*n + j
if i < n-1 {
bottom := idx + n
uf.union(idx*4+2, bottom*4)
}
if j < n-1 {
right := idx + 1
uf.union(idx*4+1, right*4+3)
}
if grid[i][j] == '/' {
uf.union(idx*4, idx*4+3)
uf.union(idx*4+1, idx*4+2)
} else if grid[i][j] == '\\' {
uf.union(idx*4, idx*4+1)
uf.union(idx*4+2, idx*4+3)
} else {
uf.union(idx*4, idx*4+1)
uf.union(idx*4+1, idx*4+2)
uf.union(idx*4+2, idx*4+3)
}
}
}
return uf.setCount
}
|