Show problems as
Classic problem #661EasyArrayMatrix

Image Smoother

Real-world version: Softening A Grey Level Scan
Tracked in this browser only
Read Image Smoother on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A scanner returns img, a grid of grey levels with m rows and n columns. img[r][c] is the grey level recorded at row r, column c.

Softening the scan replaces the level at each cell with the average level over a block: the cell itself together with every cell that touches it, sideways, vertically or diagonally, so at most nine cells. Positions that would sit outside the grid are left out of both the sum and the count. Round each average down to a whole number. Return the softened grid, which has the same shape as img. Every average is taken from the original levels, not from levels already softened.

Examples

Example 1

Input
img = [[1, 2, 3, 4]]
Output
[[1, 2, 3, 3]]

The grid has one row. Column 0 averages 1 and 2, which rounds down to 1. Column 1 averages 1, 2 and 3, giving 2. Column 2 averages 2, 3 and 4, giving 3. Column 3 averages 3 and 4, which rounds down to 3.

Example 2

Input
img = [[10], [20], [30]]
Output
[[15], [20], [25]]

The grid has one column. Row 0 averages 10 and 20, giving 15. Row 1 averages all three levels, giving 20. Row 2 averages 20 and 30, giving 25.

Example 3

Input
img = [[8, 3, 9], [1, 7, 2], [6, 4, 5], [2, 2, 2]]
Output
[[4, 5, 5], [4, 5, 5], [3, 3, 3], [3, 3, 3]]

The corner cell at row 0 column 0 averages the four levels 8, 3, 1 and 7, which is 4 after rounding down. The interior cell at row 1 column 1 averages all nine levels 8, 3, 9, 1, 7, 2, 6, 4 and 5, which is 5 after rounding down.

Constraints

  • m == img.length
  • n == img[i].length
  • 1 <= m, n <= 200
  • 0 <= img[i][j] <= 255

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def image_smoother(img: list[list[int]]) -> list[list[int]]:
Java
public int[][] imageSmoother(int[][] img)