11// Time: O(m * n * log(m + n)) ~ O(m * n * log(m * n))
22// Space: O(m * n)
33
4- // BFS with priority queue (min heap), refactored version.
54class Solution {
65public:
76 /* *
87 * @param heights: a matrix of integers
98 * @return: an integer
109 */
1110 int trapRainWater (vector<vector<int >> &heights) {
12- // Init m_, n_, is_visited_.
1311 m_ = heights.size ();
12+ if (!m_) {
13+ return 0 ;
14+ }
1415 n_ = heights[0 ].size ();
16+ if (!n_) {
17+ return 0 ;
18+ }
19+
1520 is_visited_ = vector<vector<bool >>(m_, vector<bool >(n_, false ));
1621
1722 int trap = 0 ;
1823
1924 // Put the cells on the border into min heap.
2025 for (int i = 0 ; i < m_; ++i) {
2126 heap_.emplace (Cell{i, 0 , heights[i][0 ]});
27+ is_visited_[i][0 ] = true ;
2228 heap_.emplace (Cell{i, n_ - 1 , heights[i][n_ - 1 ]});
29+ is_visited_[i][n_ - 1 ] = true ;
2330 }
2431 for (int j = 0 ; j < n_; ++j) {
2532 heap_.emplace (Cell{0 , j, heights[0 ][j]});
33+ is_visited_[0 ][j] = true ;
2634 heap_.emplace (Cell{m_ - 1 , j, heights[m_ - 1 ][j]});
35+ is_visited_[m_ - 1 ][j] = true ;
2736 }
2837 const vector<pair<int , int >> directions{{0 , -1 }, {0 , 1 },
2938 {-1 , 0 }, {1 , 0 }};
3039 // BFS with priority queue (min heap)
3140 while (!heap_.empty ()) {
3241 Cell c = heap_.top ();
3342 heap_.pop ();
34- is_visited_[c.i ][c.j ] = true ;
3543 for (const auto & d : directions) {
3644 trap += fill (heights, c.i + d.first , c.j + d.second , c.height );
3745 }
@@ -49,8 +57,8 @@ class Solution {
4957
5058 // Fill unvisited cell.
5159 if (!is_visited_[i][j]) {
52- is_visited_[i][j] = true ; // Marked as visited.
5360 heap_.emplace (Cell{i, j, max (height, heights[i][j])});
61+ is_visited_[i][j] = true ; // Marked as visited.
5462 return max (0 , height - heights[i][j]); // Fill in the gap.
5563 }
5664
0 commit comments