Ctrl K

Neighbourhood Sums in a Grid

Medium
You get an m × n table of numbers grid and an integer radius. For every cell (i, j), compute the sum of all cells (r, c) with |r − i| ≤ radius and |c − j| ≤ radius, that is, the square of side 2 · radius + 1 centred on that cell. Cells beyond the edge of the table are simply left out. Return a table of the same size where each cell holds its sum.
Example 1
grid=[[2, 0, 1], [3, 4, 1]], radius=1 → [[9, 11, 6], [9, 11, 6]]

For cell (0, 0) the square covers rows 0–1 and columns 0–1: 2 + 0 + 3 + 4 = 9. For cell (0, 1) it covers the whole table, 11. For cell (0, 2) it covers columns 1–2: 0 + 1 + 4 + 1 = 6. The second row matches, since there are only two rows.

Example 2
grid=[[5, 7], [1, 3]], radius=0 → [[5, 7], [1, 3]]

With radius 0 every cell sees only itself.

Constraints
  • 1 ≤ m, n ≤ 200
  • 0 ≤ radius ≤ 100
  • 0 ≤ grid[i][j] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLargest Light Square MediumK-th Largest Corner XOR MediumThree Heaviest Diamonds MediumBalanced Square in a Grid MediumCoin Race on Two Lanes Medium
loading Python…
Input
grid=[[2, 0, 1], [3, 4, 1]], radius=1
Expected
[[9, 11, 6], [9, 11, 6]]

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.