Problem · Matrix

Matrix Region Sum

Learn this problem
MediumRipplingOA

Problem statement

Given an integer matrix matrix and a non-negative region radius r, construct an output matrix of the same size.

For each cell (row, col), sum every input cell (i, j) satisfying:

row - r <= i <= row + r
col - r <= j <= col + r

Only coordinates inside the matrix are included. The center cell is included in its own sum.

Function

matrixRegionSum(matrix: int[][], r: int) → int[][]

Examples

Example 1

matrix = [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]r = 1return = [[4,6,6,6,4],[6,9,9,9,6],[6,9,9,9,6],[4,6,6,6,4]]

The top-left cell sees the clipped 2 x 2 region and has sum 4. Interior cells see a full 3 x 3 region and have sum 9.

Example 2

matrix = [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]r = 2return = [[9,12,15,12,9],[12,16,20,16,12],[12,16,20,16,12],[9,12,15,12,9]]

With radius 2, the center columns include all five input columns while edge cells use clipped regions.

Constraints

  • 1 <= matrix.length, matrix[0].length <= 1000
  • 0 <= r <= 1000
  • All output sums fit in a signed 32-bit integer.

More Rippling problems

drafts saved locally
public int[][] matrixRegionSum(int[][] matrix, int r) {
  // write your code here
}
matrix[[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]
r1
expected[[4,6,6,6,4],[6,9,9,9,6],[6,9,9,9,6],[4,6,6,6,4]]
checking account