Use a prefix sum array to efficiently calculate the sum of elements within any submatrix. The prefix sum array P[i][j] will store the sum of elements in the submatrix starting from (0, 0) to (i, j).
For each element in the answer matrix, use the prefix sum array to calculate the sum of elements within the given distance k.
classSolution:
defmatrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
answer = [[0] * n for _ in range(m)]
prefix_sum = [[0] * (n +1) for _ in range(m +1)]
# Compute the prefix sum arrayfor i in range(1, m +1):
for j in range(1, n +1):
prefix_sum[i][j] = mat[i-1][j-1] + prefix_sum[i-1][j] + prefix_sum[i][j-1] - prefix_sum[i-1][j-1]
# Compute the result matrixfor i in range(m):
for j in range(n):
r1 = max(0, i - k)
c1 = max(0, j - k)
r2 = min(m -1, i + k)
c2 = min(n -1, j + k)
answer[i][j] = prefix_sum[r2+1][c2+1] - prefix_sum[r1][c2+1] - prefix_sum[r2+1][c1] + prefix_sum[r1][c1]
return answer
⏰ Time complexity: O(m * n), where m is the number of rows and n is the number of columns, as we preprocess the matrix to create the prefix sum array and then compute the result matrix.
🧺 Space complexity: O(m * n), for storing the prefix sum array and the result matrix.