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
| class Solution { public: int trapRainWater(vector<vector<int>>& heightMap) { int m = heightMap.size(); int n = heightMap[0].size();
if (m < 3 || n < 3) return false; vector<vector<bool>> vis(m, vector<bool>(n, false)); priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int> > > > q; for (int i = 0; i < m; ++i) { vis[i][0] = true; vis[i][n-1] = true; q.push(make_pair(heightMap[i][0], make_pair(i, 0))); q.push(make_pair(heightMap[i][n-1], make_pair(i, n-1))); } for (int j = 0; j < n; ++j) { vis[0][j] = true; vis[m-1][j] = true; q.push(make_pair(heightMap[0][j], make_pair(0, j))); q.push(make_pair(heightMap[m-1][j], make_pair(m-1, j))); } const vector<pair<int, int>> directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; auto check = [m, n](int x, int y) { return 0 <= x && x < m && 0 <= y && y < n; };
int ret = 0; while (!q.empty()) { auto tmp = q.top(); q.pop(); int h = tmp.first; int x = tmp.second.first; int y = tmp.second.second; for (auto par : directions) { int dx = par.first; int dy = par.second; if (check(x+dx, y+dy) && !vis[x+dx][y+dy]) { vis[x+dx][y+dy] = true; if (heightMap[x+dx][y+dy] < h) { ret += h - heightMap[x+dx][y+dy]; q.push(make_pair(h, make_pair(x+dx, y+dy))); } else { q.push(make_pair(heightMap[x+dx][y+dy], make_pair(x+dx, y+dy))); } } } } return ret; } };
|