题目描述:
给你一个 m x n
的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
示例:
输入: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
输出: 4
解释: 下雨后,雨水将会被上图蓝色的方块中。总的接雨水量为1+2+1=4。
输入: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
输出: 10
解析:
方法: 最小堆 思路与算法
本题为经典题目,解题的原理和方法都可以参考「42.接雨水」,本题主要从一维数组变成了二维数组。
首先我们思考一下什么样的方块一定可以接住水:
该方块不为最外层的方块;
该方块自身的高度比其上下左右四个相邻的方块接水后的高度都要低;
我们假设方块的索引为 (i,j)(i,j),方块的高度为 \textit{heightMap}[i][j]heightMap[i][j],方块接水后的高度为 \textit{water}[i][j]water[i][j]。则我们知道方块 (i,j)(i,j) 的接水后的高度为:
\textit{water}[i][j] = \max(\textit{heightMap}[i],\min(\textit{water}[i-1][j],\textit{water}[i+1][j],\textit{water}[i][j-1],\textit{water}[i][j+1]))
water[i][j]=max(heightMap[i],min(water[i−1][j],water[i+1][j],water[i][j−1],water[i][j+1]))
我们知道方块 (i,j)(i,j) 实际接水的容量计算公式为 \textit{water}[i][j] - \textit{heightMap}[i][j]water[i][j]−heightMap[i][j]。
首先我们可以确定的是,矩阵的最外层的方块接水后的高度就是方块的自身高度,因为最外层的方块无法接水,因此最外层的方块 \textit{water}[i][j] = \textit{heightMap}[i][j]water[i][j]=heightMap[i][j]。
根据木桶原理,接到的雨水的高度由这个容器周围最短的木板来确定的。我们可以知道容器内水的高度取决于最外层高度最低的方块,
我们假设已经知道最外层的方块接水后的高度的最小值,则此时我们根据木桶原理,肯定可以确定最小高度方块的相邻方块的接水高度。我们同时更新最外层的方块标记,我们在新的最外层的方块再次找到接水后的高度的最小值,同时确定与其相邻的方块的接水高度,
然后再次更新最外层,依次迭代直到求出所有的方块的接水高度,即可知道矩阵中的接水容量。
代码:
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
if len(heightMap) <= 2 or len(heightMap[0]) <= 2:
return 0
m, n = len(heightMap), len(heightMap[0])
visited = [[0 for _ in range(n)] for _ in range(m)]
pq = []
for i in range(m):
for j in range(n):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
visited[i][j] = 1
heapq.heappush(pq, (heightMap[i][j], i * n + j))
res = 0
dirs = [-1, 0, 1, 0, -1]
while pq:
height, position = heapq.heappop(pq)
for k in range(4):
nx, ny = position // n + dirs[k], position % n + dirs[k + 1]
if nx >= 0 and nx < m and ny >= 0 and ny < n and visited[nx][ny] == 0:
if height > heightMap[nx][ny]:
res += height - heightMap[nx][ny]
visited[nx][ny] = 1
heapq.heappush(pq, (max(height, heightMap[nx][ny]), nx * n + ny))
return res