Question
在 Leetcode 的 Topic: Array 下做一道题
Answer
'''
LeetCode
Topic: Array
407. Trapping Rain Water II
Description:
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.
'''
class Solution:
"""
type heightMap: List[List[int]]
return type: int
"""
def trapRainWater(self, heightMap):
'''
Solution:
BFS.
记矩形的高度、宽度分别为m, n,令二维数组peakMap[i][j] = ∞,表示矩形区域最
多可以达到的水面高度
将矩形的四条边中的各点坐标加入队列q,并将各点对应的高度赋值给peakMap相同坐标
每次从q中弹出队头元素x, y,探索其上、下、左、右四个方向nx, ny:
尝试用max(peakMap[x][y], heightMap[nx][ny]) 更新 peakMap[nx][ny] 的当
前值(取两者中的较小值)
'''
m = len(heightMap)
n = len(heightMap[0]) if m else 0
peakMap = [[0x7FFFFFFF] * n for _ in range(m)]
q = []
for x in range(m):
for y in range(n):
if x in (0, m - 1) or y in (0, n - 1):
peakMap[x][y] = heightMap[x][y]
q.append((x, y))
while q:
x, y = q.pop(0)
for dx, dy in zip((1, 0, -1, 0), (0, 1, 0, -1)):
nx, ny = x + dx, y + dy
if nx <= 0 or nx >= m - 1 or ny <= 0 or ny >= n - 1: continue
limit = max(peakMap[x][y], heightMap[nx][ny])
if peakMap[nx][ny] > limit:
peakMap[nx][ny] = limit
q.append((nx, ny))
return sum(peakMap[x][y] - heightMap[x][y] for x in range(m) for y in range(n))
结果: