Skip to the code
cf.
+25 XP

#53 Neighborhood Totals

medium

An image filter replaces each pixel with the total of all pixels within k rows and k columns of it (a square around it, cut off at the image's edges). The pixel values are in grid.

Write neighborhoodTotals(grid, k) that returns a new grid of the same size where cell (r, c) is the total of every grid[i][j] with |i - r| <= k and |j - c| <= k.

Example 1

Input: grid = [[1,0,2],[0,3,0],[4,0,5]], k = 1
Output: [[4,6,5],[8,15,10],[7,12,8]]

The center cell sees the whole grid (15). The top-left cell sees only 1 + 0 + 0 + 3 = 4.

Example 2

Input: grid = [[5]], k = 3
Output: [[5]]

The square is cut off at the edges, so it only holds the one pixel.

Constraints

  • 1 <= rows, cols <= 100
  • 0 <= k <= 100
  • 0 <= grid[r][c] <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).