思路:本人是看了B站视频才获得解答
// Bzhan 视频:https:www.bilibili.com/video/av80545040?from=search&seid=17893266060819984383
- 木桶效应
- 从四周向中间扩散,DFS思想
- 在更新时需注意,更新后的位置高度为目前值和扩散位置的最大高度
- 具体可以看视频。不细写了免得重复。
//407.
// Bzhan 视频:https:www.bilibili.com/video/av80545040?from=search&seid=17893266060819984383
// 木桶效应:从外界往内届扩散,并记录积水
class TrapNode {
private:
public:
int value;
int x, y;
TrapNode(int value, int x, int y) :value(value), x(x), y(y) {}
~TrapNode() {}
};
class compare407{
public:
bool operator()(const TrapNode& t1, const TrapNode& t2) {
return t1.value > t2.value;
}
};
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.size() == 0 || heightMap[0].size() == 0) return 0;
int n = heightMap.size(), m = heightMap[0].size();
vector<vector<bool>> visit(n, vector<bool>(m, false));
priority_queue<TrapNode,vector<TrapNode>, compare407> chip;
vector<int> dx{ 1,0,-1, 0 };
vector<int> dy{ 0,1,0, -1 };
for (int y = 0; y < m; ++y) {
chip.push(TrapNode(heightMap[0][y], 0, y)); visit[0][y] = true;
chip.push(TrapNode(heightMap[n-1][y], n-1, y)); visit[n-1][y] = true;
}
for (int x = 1; x < heightMap.size() - 1; ++x) {
chip.push(TrapNode(heightMap[x][0], x, 0)); visit[x][0] = true;
chip.push(TrapNode(heightMap[x][m - 1], x,m - 1)); visit[x][m- 1] = true;
}
int res = 0;
while (!chip.empty()) {
TrapNode node = chip.top(); chip.pop();
for (int i = 0; i < 4; ++i) {
int x = node.x + dx[i], y = node.y + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && !visit[x][y]) {
visit[x][y] = true;
chip.push(TrapNode(max(node.value,heightMap[x][y]), x, y));
res += max(0, node.value-heightMap[x][y]);
}
}
}
return res;
}