For every cell, inspect the bounded three-by-three neighborhood, accumulate its sum and count, and write the integer average to a new matrix.
Complexity
O(rows * columns) time and O(rows * columns) output space.
Replace each image cell with the floor of the average over its valid neighboring cells.
For every cell, inspect the bounded three-by-three neighborhood, accumulate its sum and count, and write the integer average to a new matrix.
O(rows * columns) time and O(rows * columns) output space.
package main
func imageSmoother(img [][]int) [][]int {
rows, columns := len(img), len(img[0])
result := make([][]int, rows)
for row := 0; row < rows; row++ {
result[row] = make([]int, columns)
for column := 0; column < columns; column++ {
sum, count := 0, 0
for r := maxInt(0, row-1); r <= minInt(rows-1, row+1); r++ {
for c := maxInt(0, column-1); c <= minInt(columns-1, column+1); c++ {
sum += img[r][c]
count++
}
}
result[row][column] = sum / count
}
}
return result
}
func minInt(a int, b int) int {
if a < b {
return a
}
return b
}
func maxInt(a int, b int) int {
if a > b {
return a
}
return b
}
class Solution:
def imageSmoother(self, img: list[list[int]]) -> list[list[int]]:
rows, columns = len(img), len(img[0])
result = [[0] * columns for _ in range(rows)]
for row in range(rows):
for column in range(columns):
values = [img[r][c] for r in range(max(0, row - 1), min(rows, row + 2)) for c in range(max(0, column - 1), min(columns, column + 2))]
result[row][column] = sum(values) // len(values)
return result
function imageSmoother(img: number[][]): number[][] {
return img.map((row, r) => row.map((_, c) => {
let sum = 0;
let count = 0;
for (let rr = Math.max(0, r - 1); rr <= Math.min(img.length - 1, r + 1); rr += 1) {
for (let cc = Math.max(0, c - 1); cc <= Math.min(row.length - 1, c + 1); cc += 1) { sum += img[rr][cc]; count += 1; }
}
return Math.floor(sum / count);
}));
}