Matrix block sum

Write codeMedium25 min

Your task

Given an m x n integer matrix mat and an integer k, return a matrix answer where answer[i][j] is the sum of all elements mat[r][c] with i-k <= r <= i+k and j-k <= c <= j+k, clamped to the matrix bounds. In other words, each output cell sums the (2k+1) x (2k+1) block centered on it, truncated at the edges. Values may be negative; the matrix has at least one row and column and k >= 0.

Examples

matrix_block_sum(mat: list[list[int]], k: int) -> list[list[int]]
Example 1
Inputmatrix_block_sum([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1)
Output[[12, 21, 16], [27, 45, 33], [24, 39, 28]]