相关问题
11. Container With Most Water
42. Trapping Rain Water
407. Trapping Rain Water II
Discription
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
思路
BFS
想象一下,随着持续降雨,水平面不断上升。随着水位上升,外界的水逐渐淹没小岛边缘,并填满低洼处,最后直至淹没小岛的最高处。
具体通过最小栈实现。
首先将小岛的边缘加入最小栈,如下图红色部分。假设此时水位为
ϵ
> 0, 则所有边缘的土地都将被打湿(与外界水直接接触)。
取出并丢弃栈顶元素(下图绿色部分),不妨设其高度为h,当水面上升至
h+ϵ
时,开始从当前位置浸湿相邻干涩的土地。
若相邻干涩土地高于
h+ϵ
, 则加入最小堆。
继续从栈顶取出并丢弃栈顶元素(下图绿色部分),水位上升
若相邻干涩土地低于此时水位
h+ϵ
, 则水将倒灌直至填满
h+ϵ
,如下图蓝色部分。将该土地加入最小堆(高度为h)。
重复以上步骤直至淹没(栈为空)。
以上图片来自Grandyang的博客
时间复杂度:
?
空间复杂度:
代码
typedef struct unit {
int r, c, h;
unit(int _r, int _c, int _h) : r(_r), c(_c), h(_h) {}
}unit;
class cmp {
public:
bool operator()(const unit &a, const unit &b)
{
return a.h > b.h;
}
};
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.size() <= 1 || heightMap[0].size() <= 1)
return 0;
int rows = heightMap.size(), cols = heightMap[0].size();
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
priority_queue<unit, vector<unit>, cmp> que;
vector<pair<int, int>> directions = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };
for (int i = 0; i < rows; i++)
{
visited[i][0] = true;
visited[i][cols - 1] = true;
que.push(unit(i, 0, heightMap[i][0]));
que.push(unit(i, cols - 1, heightMap[i][cols - 1]));
}
for (int j = 1; j < cols - 1; j++)
{
visited[0][j] = true;
visited[rows - 1][j] = true;
que.push(unit(0, j, heightMap[0][j]));
que.push(unit(rows - 1, j, heightMap[rows - 1][j]));
}
int sum = 0;
while (!que.empty())
{
unit tmp = que.top();
que.pop();
for (int i = 0; i < directions.size(); i++)
{
int r = tmp.r + directions[i].first;
int c = tmp.c + directions[i].second;
if (0 <= r && r < rows && 0 <= c && c < cols && !visited[r][c])
{
int h = heightMap[r][c];
visited[r][c] = true;
if (h < tmp.h) //灌水
{
sum += tmp.h - h;
h = tmp.h;
}
que.push(unit(r, c, h));
}
}
}
return sum;
}
};