File: image-smoother/solution.py

Date: 2026-06-06

Time: 17:02

image-smoother/solution.py

Purpose

This file solves LeetCode 661 — Image Smoother. It applies a 3×3 box blur filter to a grayscale image matrix: each cell is replaced by the floor of the average of itself and its valid neighbors. The file is self-contained — solution and tests in one module.

Key Components

Solution.imageSmoother(img) — The core algorithm. Takes an m × n matrix of integers (0–255) and returns a new matrix of the same dimensions where each cell holds floor(sum of neighbors / count of neighbors). "Neighbors" means the cell itself plus all adjacent cells within a 3×3 window, clamped to matrix bounds.

TestImageSmoother — Seven test cases covering the LeetCode examples, degenerate shapes (1×1, single row, single column), and uniform matrices (all-zero, all-255).

Patterns

Brute-force convolution with boundary clamping. Rather than padding the matrix or pre-checking edge/corner cases, the inner loop uses max(0, i-1) and min(m, i+2) to define the window bounds. This idiom eliminates branch logic for borders — the window naturally shrinks from 3×3 to 2×3, 2×2, etc. at edges.

Out-of-place computation. A fresh result matrix is allocated up front, so reads from img are never corrupted by writes. This avoids the complexity of in-place approaches that encode old and new values in a single cell (a common LeetCode trick using bit packing).

Inline tests. The unittest suite lives in the same file with if _name == "main": unittest.main(), matching the repo-wide convention. A separate testsolution.py also exists for each problem directory.

Dependencies

Imports: typing.List (type annotation) and unittest (test framework). No external packages.

Imported by: The "Imported By" list in the prompt is misleading — it shows hundreds of unrelated test files. These are likely artifacts of a static analysis tool matching on from solution import Solution across the entire repo, not actual consumers of *this* solution. The real dependent is image-smoother/test_solution.py.

Flow

1. Read dimensions m, n from the input matrix.

2. Allocate a zeroed m × n result matrix.

3. For each cell (i, j):

4. Return the result matrix.

The time complexity is O(m·n) — the inner 3×3 window is bounded at 9 iterations regardless of matrix size. Space is O(m·n) for the output.

Invariants

Error Handling

None. The function trusts its caller to provide a valid non-empty matrix of integers. This is standard for LeetCode solutions where input constraints are guaranteed by the judge. Passing an empty matrix would raise an IndexError on len(img[0]).

Topics to Explore

Beliefs