Image Smoother
You have a grid filled with numbers, which we will call an “image”. You are asked to create a new image where the value of each cell is the average of itself and its neighbors. However, if a cell doesn’t have a neighbor in any direction (because it’s on the edge), just ignore that nonexisting neighbor when computing the average.
For instance, the cell at the top left corner has only three neighbors (right, downright, down), while a cell in the middle of the image has eight neighbors (up, down, left, right, and all the four diagonals).
The goal is to create a new image with these averaged values. Round down the average if it’s not an integer.
Abstract Representation of the Problem
We are given a twodimensional grid of integers. For each cell in the grid, we need to calculate a new value based on the values of its surrounding cells. Specifically, the new value should be the floor of the average of the cell’s own value and the values of its immediate neighbors (up to 8 neighbors: topleft, top, topright, right, bottomright, bottom, bottomleft, left).
If a cell is at the edge of the grid, it may have fewer than 8 neighbors. In this case, the average should be calculated based only on the available neighbors and the cell itself.
The goal is to create a new grid where each cell’s value is replaced with this calculated average.
This abstract representation emphasizes the key elements of spatial relationship between cells in a grid and the operation of calculating a new value based on immediate neighborhood. The specifics of the image smoothing application have been abstracted away.
Identifying Problem Isomorphism
“Image Smoother” has an approximate isomorphism: “Cell Compete” on Amazon OAs.
In “Image Smoother”, given a 2D integer matrix M representing the gray scale of an image, you are to design a smoother to make the image smoother. A cell’s next state is set to the average of itself and all its 8 surrounding cells’ current states.
Similarly, in “Cell Compete”, an array represents cells in a row (1 active, 0 inactive), and each cell’s next state is set to be the opposite of its current state if its two neighboring cells are either both active or both inactive. Otherwise, it remains the same.
Both problems require applying a rule to each element in a structure (2D matrix or 1D array) based on its neighboring elements. The update rule differs but the fundamental concept is identical.
“Image Smoother” is a little more complex because you have to handle a 2D matrix and eight possible neighbors, while “Cell Compete” has a 1D array and just two neighbors.
Solution
To solve this problem, you can iterate over each cell in the image and find the average of the surrounding cells including itself. Then, assign the floor of the average to the cell in the resulting image.
Here is the Python code for it:


In this code, directions
list includes the current cell and its 8 surrounding cells. We iterate over each cell in the image. For each cell, we calculate the total sum of the values of the cell and its valid surrounding cells and keep count of the number of valid cells. Then, we calculate the average and assign it to the corresponding cell in the resulting image.
We’re using //
operator for floor division to get the rounded down average.
The innermost loop has the job of moving through all the neighboring cells of a given cell in the image grid.
Specifically, it scans the cells that are within one unit distance, horizontally, vertically, or diagonally, from the current cell. It calculates the sum of the values of these cells and counts how many valid neighbors the cell has.
It’s necessary to handle cases where the current cell is at the edge of the image, as it would have fewer than eight neighbors. The loop ensures that we only consider valid neighbors within the image boundaries for the sum and count.
The innermost loop performs the image smoothing operation for a single cell at a time.
The i
and j
are indices used to navigate through the 2D list or matrix, img
.
i
is used to represent the current row index in the image.j
is used to represent the current column index in the image.
So img[i][j]
refers to the element at the i
th row and j
th column in the image. This is a common way to traverse a 2D list or matrix in programming, often visualized as moving through the rows and columns of a grid.
The first two for loops are for traversing the given image matrix. They iterate over each cell in the matrix.
 The outer loop,
for i in range(m)
, iterates over each row of the matrix.m
is the total number of rows in the image.  The inner loop,
for j in range(n)
, iterates over each column of the matrix.n
is the total number of columns in the image.
So, i
and j
together give us access to every cell in the matrix. With this setup, we can process each cell of the image individually, which is required for the image smoothing operation. The processing part happens within these loops.


Problem Classification
This problem falls into the domain of Image Processing. The task is to apply a smoothing filter to an image, where each pixel in the image is treated as a cell in a matrix.
‘What’ Components:
An m x n integer matrix img representing the grayscale of an image: This is the input to our problem and represents a grayscale image. The values can be thought of as pixel intensity levels.
The image smoother is a 3 x 3 filter that can be applied to each cell of an image: This indicates the operation we have to perform on each cell (pixel) of the image. Each cell’s new value will be the floor of the average of its own and its surrounding cells’ values.
If one or more of the surrounding cells of a cell is not present, we do not consider it in the average: This is a special rule that tells us what to do at the edges of the image, where there aren’t enough surrounding cells to form a full 3x3 filter.
Return the image after applying the smoother on each cell of it: This is the desired output, a new image where each pixel’s value has been replaced by the average of its neighbors.
This is a Spatial Transformation problem in Image Processing. Spatial transformations deal with modifying the pixel values based on their neighborhoods. In this problem, the neighborhood is defined as the 3 x 3 matrix centered on the pixel, and the modification is the application of the smoother (calculating the average pixel value).
Language Agnostic Coding Drills
Dissection of the Code:
a. Checking for empty input: The code begins with a check to determine if the input matrix
M
or its first row is empty. If so, it returns an empty matrix.b. Matrix dimension retrieval: The code retrieves the dimensions of the matrix (m x n) using the builtin Python function
len()
.c. Directions array: The code creates a 2D array
dirs
representing the eight possible directions (top, bottom, left, right, topleft, topright, bottomleft, bottomright) in a 2D grid.d. Matrix creation: The code creates an m x n matrix
res
of zeros.e. Nested loops: The code uses two nested loops to iterate over each cell of the matrix.
f. Cell calculation: For each cell, it computes the sum and count of the cell and its neighbors, based on the directions defined.
g. Boundary check: The code includes a check to prevent outofbounds array access.
h. Final cell value assignment: The code assigns the computed average to the corresponding cell in the result matrix
res
.Concepts Ordered by Increasing Difficulty:
a. Empty input check (easy): Involves checking if an input data structure is empty.
b. Matrix dimension retrieval (easy): Involves using builtin Python functions to determine the size of an array.
c. Matrix creation (easy): Creating a 2D array of a specified size and initializing it with a default value.
d. Nested loops (medium): Involves using nested loops to iterate over 2D arrays. It’s a bit trickier than the previous concepts as it involves maintaining correct indices.
e. Cell calculation and boundary check (medium): Involves performing arithmetic operations, and ensuring array access is within bounds.
f. Direction array (medium): Using an array of directions to access neighboring elements in a grid. This is a concept widely used in gridbased problems.
ProblemSolving Approach:
The problem at hand is a classical grid traversal problem, where a computation needs to be performed for each cell based on its neighboring cells. Here are the steps:
a. First, we check if the input matrix is empty. If so, we return an empty matrix.
b. We then retrieve the dimensions of the input matrix.
c. We create a directions array to ease the traversal of neighbors.
d. We create a result matrix of the same size as the input matrix, initialized with zeros.
e. We then iterate over each cell of the matrix, for each cell, we calculate the sum and count of the cell and its valid (within bounds) neighbors.
f. Finally, we compute the average by dividing the sum by the count and assign this value to the corresponding cell in the result matrix.
g. We return the result matrix after the completion of the computation for all cells.
Each of the concepts identified contributes to the solution. Concepts like matrix creation, nested loops, and cell calculations are fundamental to gridbased problems like this one. The direction array, in particular, is a powerful concept that simplifies accessing neighbors in a grid.
Targeted Drills in Python
Python Code Drills for Identified Concepts:
a. Empty Input Check:
1 2
def is_empty(data): return not bool(data)
b. Matrix Dimension Retrieval:
1 2
def matrix_dimensions(matrix): return len(matrix), len(matrix[0])
c. Matrix Creation:
1 2
def create_matrix(m, n, val=0): return [[val for _ in range(n)] for _ in range(m)]
d. Nested Loops:
1 2 3 4
def traverse_matrix(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): print(matrix[i][j])
e. Cell Calculation and Boundary Check:
1 2 3 4 5 6 7 8 9 10
def cell_sum(matrix, i, j, dirs): sum_ = matrix[i][j] cnt = 1 m, n = len(matrix), len(matrix[0]) for dir_ in dirs: x, y = i + dir_[0], j + dir_[1] if 0 <= x < m and 0 <= y < n: sum_ += matrix[x][y] cnt += 1 return sum_ // cnt
f. Direction Array:
1 2
def create_directions(): return [[0, 1], [0, 1], [1, 0], [1, 0], [1, 1], [1, 1], [1, 1], [1, 1]]
Problemspecific Concepts:
This problem doesn’t have specific coding concepts outside of the general ones identified. However, the combination of these concepts is crucial for the solution. The use of a direction array to calculate the sum and count of a cell’s neighbors is the core idea behind this problem’s solution.
Integration of Coding Drills:
The solution to this problem can be assembled by integrating the identified concepts in the following order:
a. Begin by checking if the input matrix is empty using the
is_empty()
function.b. Retrieve the dimensions of the matrix using the
matrix_dimensions()
function.c. Create a directions array using the
create_directions()
function.d. Create a result matrix using the
create_matrix()
function with the dimensions retrieved in step (b).e. Traverse each cell in the input matrix using a nested loop.
f. For each cell, calculate the average of the cell and its valid neighbors using the
cell_sum()
function and assign this value to the corresponding cell in the result matrix.g. Return the result matrix.
The above sequence of steps will give the final output, which is the image after smoothing each cell.