Matrix Block Sum
The problem is asking us to compute the sum of the elements in a block of size (2k + 1) around each cell of a given matrix mat
. Here’s a step-by-step Python solution to achieve this:
- Create a Prefix Sum Matrix: First, we’ll create a prefix sum matrix
prefix_sum
of the same size asmat
. The value atprefix_sum[i][j]
will be the sum of all elements inmat
that are in the top-left rectangle formed by (0,0) to (i,j). - Use Prefix Sum to Compute Block Sum: Next, we’ll compute the block sum for each position
(i,j)
using the prefix sum matrix. We’ll define four corner points of the block and use them to get the sum using the prefix sum matrix. - Return the Result: The computed block sum for each
(i,j)
will be the result, and we’ll return it.
Here’s the code:
|
|
This solution will compute the required block sum for the entire matrix, adhering to the constraints and conditions mentioned in the problem statement.