53
53
*
54
54
*/
55
55
56
+ #include < algorithm>
57
+ #include < array>
58
+ #include < functional>
56
59
#include < queue>
60
+ #include < utility>
57
61
#include < vector>
58
-
59
62
// @lc code=start
60
63
class Solution {
61
64
using pii = std::pair<int , int >;
62
65
63
- public:
66
+ public:
64
67
int trapRainWater (std::vector<std::vector<int >> &heightMap) {
68
+ int res = 0 ;
65
69
if (heightMap.size () < 3 || heightMap[0 ].size () < 3 ) {
66
- return 0 ;
70
+ return res ;
67
71
}
68
- std::priority_queue<pii, std::vector<pii>, std::greater<pii>> q;
69
72
int m = heightMap.size ();
70
73
int n = heightMap[0 ].size ();
71
74
std::vector<bool > visited (m * n, false );
75
+ std::priority_queue<pii, std::vector<pii>, std::greater<pii>> q;
76
+
72
77
// check edge
73
78
for (int i = 0 ; i < m; i++) {
74
79
for (int j = 0 ; j < n; j++) {
@@ -80,23 +85,20 @@ class Solution {
80
85
}
81
86
}
82
87
83
- // check all block
84
- int res = 0 ;
85
- int dir[] = {-1 , 0 , 1 , 0 , -1 }; // left/bottom/right/top
88
+ int dirs[] = {-1 , 0 , 1 , 0 , -1 };
89
+ // check every grid
86
90
while (!q.empty ()) {
87
- pii cur = q.top ();
91
+ auto cur = q.top ();
88
92
q.pop ();
89
- for (int k = 0 ; k < 4 ; k++) {
90
- int x = cur.second / n + dir[k];
91
- int y = cur.second % n + dir[k + 1 ];
92
- int xyi = x * n + y;
93
- if (x >= 0 && x < m && y >= 0 && y < n &&
94
- !visited[xyi]) { // not edge
95
- if (heightMap[x][y] < cur.first ) {
96
- res += cur.first - heightMap[x][y];
97
- }
98
- visited[xyi] = true ;
99
- q.push ({std::max (heightMap[x][y], cur.first ), xyi});
93
+
94
+ for (int k = 0 ; k < 4 ; k++) { // check left/down/right/up
95
+ int x = cur.second / n + dirs[k];
96
+ int y = cur.second % n + dirs[k + 1 ];
97
+ int idx = x * n + y;
98
+ if (x >= 0 && x < m && y >= 0 && y < n && !visited[idx]) {
99
+ res += cur.first > heightMap[x][y] ? cur.first - heightMap[x][y] : 0 ;
100
+ visited[idx] = true ;
101
+ q.push ({std::max (heightMap[x][y], cur.first ), idx});
100
102
}
101
103
}
102
104
}
0 commit comments