Given an m x n
integer matrix image
representing the grayscale of an image, return a new matrix answer
of the same dimensions where:
answer[row][col]
is the average of the grayscale values of the corresponding 3x3 window with the center at image[row][col]
.
- The average should be rounded down to the nearest integer.
- If a cell is on the edge of the matrix and some elements in the 3x3 window are out of the matrix boundary, we only consider the elements that are inside the boundary for calculating the average.
Clarifying Questions
- Q: What is the range of values in the input matrix
image
?
- A: The values in the matrix can be any integer, positive or negative.
- Q: How should edge cases be handled (e.g., single-row or single-column matrices)?
- A: The calculation should only consider cells within the matrix boundaries for such edge cases.
- Q: Is there a constraint on the size of the matrix?
- A: The matrix dimensions can be any size, up to
m x n
.
Strategy
- Iterate through each cell in the matrix.
- For each cell, calculate the average of the 3x3 window centered at that cell.
- Ensure boundary checks to avoid accessing elements outside the matrix.
- Store the computed average in the corresponding cell of the result matrix.
Time Complexity
- The time complexity is
O(m * n)
because each cell in the input matrix is processed once.
- The space complexity is also
O(m * n)
since we store the results in a new matrix of the same size.
Code
def imageSmoother(image):
if not image or not image[0]:
return []
m, n = len(image), len(image[0])
result = [[0] * n for _ in range(m)]
for row in range(m):
for col in range(n):
# Initialize sum of elements and count of valid elements.
sum_val, count = 0, 0
# Iterate over the 3x3 window.
for i in range(row - 1, row + 2):
for j in range(col - 1, col + 2):
if 0 <= i < m and 0 <= j < n:
sum_val += image[i][j]
count += 1
# Calculate result for the current cell.
result[row][col] = sum_val // count
return result
Explanation
- Input and Boundary Check: The function first checks if the input exists and is non-empty.
- Matrix Dimensions: It retrieves the dimensions of the input matrix
m
(rows) and n
(columns).
- Result Initialization: A result matrix of the same size is initialized with all zeros.
- Nested Loops: Two nested loops iterate through each cell in the input matrix.
- Window Calculation: For each cell, nested loops iterate through the 3x3 window centered at that cell. Boundary checks (0 <= i < m and 0 <= j < n) ensure only valid cells are included in the sum.
- Averaging: After summing the valid cells in the window and counting them, the average (rounded down) is stored in the result matrix.
This solution ensures that all boundary conditions are respected, and the computation of the smoothed values is efficient and straightforward.
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?