解此题,可以先看看接雨水1,接雨水
力扣链接:407. 接雨水 II - 力扣(LeetCode)
给你一个 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
"""
思路:
此题在接雨水1的基础上变成3维的,我们还是计算每一个位置,在前后左右四个方向上,
找到比当前位置最高的四个挡板,最短板-当前位置高度,就是装水量
当然外部第一圈是不可能接水的,遍历的时候可以跳过
用一个数组dp来记录每一个位置的接水量,最终求和就是结果
"""
def trapRainWater(heightMap):
m = len(heightMap) # 行
n = len(heightMap[0]) # 列
# print(m, n)
dp = [[0 for i in range(n)] for j in range(m)]
# print(dp)
def get_top(i, j):
# print("*", i, j)
top_max = 0
listres = []
for _ in range(i):
listres.append(heightMap[_][j])
# print(heightMap[_][j])
top_max = max(listres)
return top_max
def get_bottom(i, j):
bottom_max = 0
listres = []
for _ in range(i + 1, len(heightMap)):
# print(heightMap[_][j])
listres.append(heightMap[_][j])
bottom_max = max(listres)
return bottom_max
def get_left(i, j):
left_max = 0
listres = []
for _ in range(j):
listres.append(heightMap[i][_])
left_max = max(listres)
return left_max
def get_right(i, j):
right_max = 0
listres = []
for _ in range(j + 1, len(heightMap[0])):
listres.append(heightMap[i][_])
right_max = max(listres)
return right_max
for i in range(1, m - 1):
for j in range(1, n - 1):
# print(i,j,heightMap[i][j],end="\n")
top_max = get_top(i, j)
bottom_max = get_bottom(i, j)
left_max = get_left(i, j)
right_max = get_right(i, j)
# print(top_max, bottom_max, left_max, right_max)
res = min(top_max, bottom_max, left_max, right_max) - heightMap[i][j]
if res > 0:
dp[i][j] = res
list_res = [dp[i][j] for j in range(n) for i in range(m)]
return sum(list_res)
heightMap1 = [[1, 4, 3, 1, 3, 2],
[3, 2, 1, 3, 2, 4],
[2, 3, 3, 2, 3, 1]]
heightres1 = [[0, 0, 0, 0, 0, 0],
[0, 1, 2, 0, 1, 0],
[0, 0, 0, 0, 0, 0]]
print(trapRainWater([[1, 4, 3, 1, 3, 2], [3, 2, 1, 3, 2, 4], [2, 3, 3, 2, 3, 1]]))
print(trapRainWater([[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]]))
heightMap2 = [[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]]
heightres2 = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 2, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]