1314. Matrix Block Sum

Given an `m x n` matrix `mat` and an integer `K`, return a matrix `answer` where each `answer[i][j]` is the sum of all elements `mat[r][c]` within `K` distance (Manhattan) of `(i,j)`. Use a 2D prefix sum to compute each block sum efficiently.

Input Format

2D list and K.

Output Format

2D list of sums.

Constraints

  • m,n ≤ 100; K ≤ 100.

Examples

Example 1:

Input:

mat = [[1,2,3],[4,5,6],[7,8,9]]
K = 1

Output:

[[12,21,16],[27,45,33],[24,39,28]]

Explanation:

Each answer[i][j] is sum of neighbors within K.

Loading...
1314. Matrix Block Sum - Matrix DSA Problem