1
- package trapping_rain_water_II
1
+ package trapping_rain_water_II
2
+
3
+ import "container/heap"
4
+
5
+ type Cell struct {
6
+ Height int
7
+ Row int
8
+ Col int
9
+ }
10
+
11
+ type MinHeap []Cell
12
+
13
+ func (h MinHeap ) Len () int { return len (h ) }
14
+ func (h MinHeap ) Less (i , j int ) bool { return h [i ].Height < h [j ].Height }
15
+ func (h MinHeap ) Swap (i , j int ) { h [i ], h [j ] = h [j ], h [i ] }
16
+
17
+ func (h * MinHeap ) Push (x interface {}) {
18
+ * h = append (* h , x .(Cell ))
19
+ }
20
+
21
+ func (h * MinHeap ) Pop () interface {} {
22
+ old := * h
23
+ n := len (old )
24
+ item := old [n - 1 ]
25
+ * h = old [0 : n - 1 ]
26
+ return item
27
+ }
28
+
29
+ func trapRainWater (heightMap [][]int ) int {
30
+ if len (heightMap ) == 0 || len (heightMap [0 ]) == 0 {
31
+ return 0
32
+ }
33
+
34
+ ROWS := len (heightMap )
35
+ COLS := len (heightMap [0 ])
36
+ minHeap := & MinHeap {}
37
+ heap .Init (minHeap )
38
+
39
+ for r := 0 ; r < ROWS ; r ++ {
40
+ for c := 0 ; c < COLS ; c ++ {
41
+ if (r == 0 || r == ROWS - 1 ) || (c == 0 || c == COLS - 1 ) {
42
+ heap .Push (minHeap , Cell {
43
+ Height : heightMap [r ][c ],
44
+ Row : r ,
45
+ Col : c ,
46
+ })
47
+ heightMap [r ][c ] = - 1
48
+ }
49
+ }
50
+ }
51
+
52
+ res := 0
53
+ maxHeight := 0
54
+
55
+ directions := [][]int {
56
+ {0 , 1 },
57
+ {0 , - 1 },
58
+ {1 , 0 },
59
+ {- 1 , 0 },
60
+ }
61
+
62
+ for minHeap .Len () > 0 {
63
+ cell := heap .Pop (minHeap ).(Cell )
64
+ maxHeight = max (maxHeight , cell .Height )
65
+ for _ , dir := range directions {
66
+ nr , nc := cell .Row + dir [0 ], cell .Col + dir [1 ]
67
+ if nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && heightMap [nr ][nc ] != - 1 {
68
+ res += max (0 , maxHeight - heightMap [nr ][nc ])
69
+ heap .Push (minHeap ,Cell {
70
+ Height : heightMap [nr ][nc ],
71
+ Row : nr ,
72
+ Col : nc ,
73
+ })
74
+ heightMap [nr ][nc ] = - 1
75
+ }
76
+ }
77
+ }
78
+
79
+ return res
80
+ }
81
+
82
+ func max (a , b int ) int {
83
+ if a > b {
84
+ return a
85
+ }
86
+ return b
87
+ }
0 commit comments