Leetcode407.接雨水2

思路:本人是看了B站视频才获得解答
// Bzhan 视频:https:www.bilibili.com/video/av80545040?from=search&seid=17893266060819984383

  1. 木桶效应
  2. 从四周向中间扩散,DFS思想
  3. 在更新时需注意,更新后的位置高度为目前值和扩散位置的最大高度
  4. 具体可以看视频。不细写了免得重复。
//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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值