You are given a m x n matrix mat and an integer k. Your task is to create a new matrix answer where each cell answer[i][j] contains the sum of all elements within a square block centered at position (i, j).
Specifically, for each position (i, j), you need to sum all elements mat[r][c] where:
i - k ≤ r ≤ i + kj - k ≤ c ≤ j + k(r, c)is a valid position within the matrix boundaries
Think of it as placing a (2k+1) x (2k+1) square window around each cell and summing all values within that window. If the window extends beyond the matrix boundaries, only consider the valid cells within the matrix.
Example: If k = 1, each cell sums a 3x3 block centered on itself.
Input & Output
Visualization
Time & Space Complexity
O(mn) to build prefix matrix + O(mn) to calculate all results = O(mn) total
Additional space needed for the prefix sum matrix
Constraints
- m == mat.length
- n == mat[i].length
- 1 ≤ m, n ≤ 300
- 1 ≤ mat[i][j] ≤ 104
- 0 ≤ k ≤ 100