LeetCode 题解工作台
矩阵区域和
给你一个 m x n 的矩阵 mat 和一个整数 k ,请你返回一个矩阵 answer ,其中每个 answer[i][j] 是所有满足下述条件的元素 mat[r][c] 的和: i - k j - k 且 (r, c) 在矩阵内。 示例 1: 输入: mat = [[1,2,3],[4,5,6],…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·matrix
答案摘要
本题属于二维前缀和模板题。 我们定义 表示矩阵 前 行,前 列的元素和。那么 的计算公式为:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个 m x n 的矩阵 mat 和一个整数 k ,请你返回一个矩阵 answer ,其中每个 answer[i][j] 是所有满足下述条件的元素 mat[r][c] 的和:
i - k <= r <= i + k,j - k <= c <= j + k且(r, c)在矩阵内。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 输出:[[12,21,16],[27,45,33],[24,39,28]]
示例 2:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 输出:[[45,45,45],[45,45,45],[45,45,45]]
提示:
m == mat.lengthn == mat[i].length1 <= m, n, k <= 1001 <= mat[i][j] <= 100
解题思路
方法一:二维前缀和
本题属于二维前缀和模板题。
我们定义 表示矩阵 前 行,前 列的元素和。那么 的计算公式为:
这样我们就可以通过 数组快速计算出任意矩形区域的元素和。
对于一个左上角坐标为 ,右下角坐标为 的矩形区域的元素和,我们可以通过 数组计算出来:
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(mat, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
x1, y1 = max(i - k, 0), max(j - k, 0)
x2, y2 = min(m - 1, i + k), min(n - 1, j + k)
ans[i][j] = (
s[x2 + 1][y2 + 1] - s[x1][y2 + 1] - s[x2 + 1][y1] + s[x1][y1]
)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m _n) with prefix sums, versus O(m_ n _k_ k) for naive approach. Space complexity is O(m*n) for the prefix sum matrix, trading extra memory for fast block sum computation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask how to compute each cell sum without repeatedly iterating the same elements.
- question_mark
Check understanding of 2D prefix sums and inclusion-exclusion for matrix blocks.
- question_mark
Probe handling of matrix edges and index boundaries in the block sum.
常见陷阱
外企场景- error
Naively summing blocks leads to timeouts on larger matrices.
- error
Incorrectly handling boundaries can produce index errors or wrong sums at edges.
- error
Forgetting to apply inclusion-exclusion when using prefix sums results in double-counted cells.
进阶变体
外企场景- arrow_right_alt
Compute maximum or average within each k-distance block instead of sum.
- arrow_right_alt
Extend to 3D matrices where each cell sum includes layers above and below.
- arrow_right_alt
Handle dynamic updates to mat with efficient recalculation of affected block sums.