[SYSU][大二下] 高级编程技术HW Week-8 Lecture-2

Question

在 Leetcode 的 Topic: Array 下做一道题


Answer

407. Trapping Rain Water II

'''
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))
结果:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值