LeetCode407. Trapping Rain Water II

本文介绍了一种计算二维高度地图中雨水可聚集体积的算法。通过分析单元格高度,利用优先队列和访问标记,从边界开始逐步填充内部区域,计算雨水体积。示例展示了3x6高度地图上雨水的聚集情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 is trapped between the blocks. The total volume of water trapped is 4.

参考资料:here

class Solution {
public:
	int trapRainWater(vector<vector<int>>& heightMap) {
		if (heightMap.empty()) return 0;
		int m = heightMap.size(), n = heightMap[0].size(), ans = 0, elevation = 0;
		vector<vector<int>> dirs{ {-1,0},{1,0},{0,-1},{0,1} };
		vector<vector<bool>> visited(m, vector<bool>(n, false));
		priority_queue < pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
					q.push({ heightMap[i][j],i * n + j });
					visited[i][j] = true;
				}
			}
		}
		while (!q.empty()) {
			pair<int, int> tmp = q.top(); q.pop();
			int h = tmp.first, r = tmp.second / n, c = tmp.second % n;
			elevation = max(elevation, h);
			for (vector<int> dir : dirs) {
				int x = r + dir[0], y = c + dir[1];
				if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
				if (elevation > heightMap[x][y]) ans += elevation - heightMap[x][y];
				visited[x][y] = true;
				q.push({ heightMap[x][y],x * n + y });
			}
		}
		return ans;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值