Image Smoother — LeetCode 661 Python Solution
- Problem
- #661
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Example
- Input
- img = [[1,1,1],[1,0,1],[1,1,1]]
- Output
- [[0,0,0],[0,0,0],[0,0,0]]
- Explanation
- For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
Python solution
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
m, n = len(img), len(img[0])
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
s = cnt = 0
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
if 0 <= x < m and 0 <= y < n:
cnt += 1
s += img[x][y]
ans[i][j] = s // cnt
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the number of rows and columns of \textit{img}, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 661. Image Smoother is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 661. Image Smoother?
- LeetCode 661. Image Smoother is rated Easy on LeetCode.
- What is the time complexity of LeetCode 661. Image Smoother?
- The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of \textit{img}, respectively.
- What is the space complexity of LeetCode 661. Image Smoother?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 661. Image Smoother cover?
- LeetCode 661. Image Smoother is tagged Array and Matrix on LeetCode.