LeetCode 题解工作台
接雨水 II
给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。 示例 1: 输入: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] 输出: 4 解释: 下雨后,雨水将会被上图蓝色…
4
题型
5
代码语言
3
相关题
当前训练重点
困难 · 图·搜索
答案摘要
接雨水问题的变种,由于矩阵的边界上的高度是确定的,因此可以将矩阵的边界上的高度加入优先队列,然后从优先队列中取出最小的高度,然后将其四周的高度与其比较,如果四周的高度小于当前高度,则可以接雨水,接雨水的体积为当前高度减去四周的高度,然后将较大的高度加入优先队列,重复上述过程,直到优先队列为空。 时间复杂度 $O(m \times n \times \log (m \times n))$,空间复杂度…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
示例 1:

输入: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] 输出: 4 解释: 下雨后,雨水将会被上图蓝色的方块中。总的接雨水量为1+2+1=4。
示例 2:

输入: 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
提示:
m == heightMap.lengthn == heightMap[i].length1 <= m, n <= 2000 <= heightMap[i][j] <= 2 * 104
解题思路
方法一:优先队列(小根堆)
接雨水问题的变种,由于矩阵的边界上的高度是确定的,因此可以将矩阵的边界上的高度加入优先队列,然后从优先队列中取出最小的高度,然后将其四周的高度与其比较,如果四周的高度小于当前高度,则可以接雨水,接雨水的体积为当前高度减去四周的高度,然后将较大的高度加入优先队列,重复上述过程,直到优先队列为空。
时间复杂度 ,空间复杂度 。其中 和 分别为矩阵的行数和列数。
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m, n = len(heightMap), len(heightMap[0])
vis = [[False] * 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:
heappush(pq, (heightMap[i][j], i, j))
vis[i][j] = True
ans = 0
dirs = (-1, 0, 1, 0, -1)
while pq:
h, i, j = heappop(pq)
for a, b in pairwise(dirs):
x, y = i + a, j + b
if x >= 0 and x < m and y >= 0 and y < n and not vis[x][y]:
ans += max(0, h - heightMap[x][y])
vis[x][y] = True
heappush(pq, (max(h, heightMap[x][y]), x, y))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(m \cdot n \times \log{m \cdot n}) |
| 空间 | O(m \times n) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates an understanding of how BFS and priority queues can be applied to 2D matrix problems.
- question_mark
The candidate identifies key edge cases and efficiently handles varying matrix sizes and elevations.
- question_mark
The candidate can explain the flow of water across different heights in a matrix and why boundary processing is crucial.
常见陷阱
外企场景- error
Failing to use a priority queue effectively may lead to inefficient traversal and incorrect water trapping calculations.
- error
Overcomplicating the problem with unnecessary space or time-consuming operations.
- error
Not handling edge cases where the matrix is very small or where the matrix has constant elevation values, which could lead to incorrect results.
进阶变体
外企场景- arrow_right_alt
Implementing the solution without a priority queue, relying on a simpler flood-fill approach.
- arrow_right_alt
Optimizing space complexity by using in-place modifications to the heightMap matrix.
- arrow_right_alt
Handling varying matrix shapes (non-square matrices) and ensuring correctness in all cases.