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 Cell struct {
x, y, h int
}
type MinHeap []Cell
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].h < h[j].h }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(Cell))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func trapRainWater(heightMap [][]int) int {
if len(heightMap) == 0 || len(heightMap[0]) == 0 {
return 0
}
m, n := len(heightMap), len(heightMap[0])
visited := make([][]bool, m)
for i := 0; i < m; i++ {
visited[i] = make([]bool, n)
}
h := &MinHeap{}
heap.Init(h)
for i := 0; i < m; i++ {
heap.Push(h, Cell{i, 0, heightMap[i][0]})
heap.Push(h, Cell{i, n - 1, heightMap[i][n - 1]})
visited[i][0] = true
visited[i][n-1] = true
}
for j := 0; j < n; j++ {
heap.Push(h, Cell{0, j, heightMap[0][j]})
heap.Push(h, Cell{m - 1, j, heightMap[m-1][j]})
visited[0][j] = true
visited[m-1][j] = true
}
ans := 0
dirs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
for h.Len() > 0 {
cell := heap.Pop(h).(Cell)
for _, d := range dirs {
x, y := cell.x+d[0], cell.y+d[1]
if x >= 0 && x < m && y >= 0 && y < n && !visited[x][y] {
visited[x][y] = true
if cell.h > heightMap[x][y] {
ans += cell.h - heightMap[x][y]
}
heap.Push(h, Cell{x, y, max(cell.h, heightMap[x][y])})
}
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|