|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + typedef pair<int, pair<int, int>> PP; |
| 4 | + vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; |
| 5 | + |
| 6 | + int trapRainWater(vector<vector<int>>& heightMap) { |
| 7 | + |
| 8 | + int m = heightMap.size(); |
| 9 | + int n = heightMap[0].size(); |
| 10 | + |
| 11 | + priority_queue<PP, vector<PP>, greater<>> boundaryCells; |
| 12 | + |
| 13 | + vector<vector<bool>> visited(m, vector<bool>(n, false)); |
| 14 | + |
| 15 | + for (int r = 0; r < m; ++r) { |
| 16 | + for (int c : {0, n - 1}) { //0 : left most boundary, cols-1 right most boundary |
| 17 | + boundaryCells.push({heightMap[r][c], {r, c}}); |
| 18 | + visited[r][c] = true; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + for (int c = 0; c < n; ++c) { |
| 23 | + for (int r : {0, m - 1}) { //0 : top most boundary, rows-1 bottom most boundary |
| 24 | + boundaryCells.push({heightMap[r][c], {r, c}}); |
| 25 | + visited[r][c] = true; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + int water = 0; |
| 30 | + |
| 31 | + while(!boundaryCells.empty()){ |
| 32 | + PP p = boundaryCells.top(); |
| 33 | + boundaryCells.pop(); |
| 34 | + |
| 35 | + int heigth = p.first; |
| 36 | + int i = p.second.first; |
| 37 | + int j = p.second.second; |
| 38 | + |
| 39 | + //find neighbourss |
| 40 | + for(vector<int>& dir: directions){ |
| 41 | + int i_ = i + dir[0]; |
| 42 | + int j_ = j + dir[1]; |
| 43 | + |
| 44 | + if(i_ >= 0 && i_ <m && j_ >= 0 && j_ <n && !visited[i_][j_]){ |
| 45 | + water += max(heigth - heightMap[i_][j_], 0); |
| 46 | + boundaryCells.push({max(heigth, heightMap[i_][j_]), {i_, j_}}); |
| 47 | + |
| 48 | + visited[i_][j_] = true; |
| 49 | + |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return water; |
| 54 | + } |
| 55 | +}; |
0 commit comments