Problem Description
Given an m x n matrix mat and an integer k, return a matrix answer where each element answer[i][j] is the sum of all elements mat[r][c] such that r and c satisfy: i - k <= r <= i + k, j - k <= c <= j + k, and (r, c) is within the bounds of the matrix.
Key Insights
- Brute-force summing every block for each element is inefficient for larger matrices.
- Using a prefix sum (cumulative sum) matrix greatly optimizes the process.
- With a prefix sum matrix, we can compute the sum of any submatrix in constant time.
- Boundary management is crucial since the k-neighborhood may extend beyond the matrix edges.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n)
Solution
We compute a prefix sum matrix where each element at (i, j) represents the sum of all elements in mat from (0, 0) to (i, j). With the prefix sum matrix, the sum of any submatrix defined by its corners can be efficiently computed using the inclusion-exclusion principle. For each element in the result matrix, the boundaries of the submatrix are determined by the limits imposed by k and the matrix size. This approach ensures that each matrix cell’s block sum is calculated in constant time after an initial O(m * n) preprocessing step for building the prefix sum matrix.