66. Image Smoother
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).
Given an m x n
integer matrix img
representing the grayscale of an image, return the image after applying the smoother on each cell of it.
Example 1:
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
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
First solv
from math import floor
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
row = len(img)
col = len(img[0])
result = [[0 for _ in range(col)] for _ in range(row)]
for r in range(row):
for c in range(col):
now_stack = []
surrounding = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]
for dx, dy in surrounding:
new_x, new_y = r + dx, c + dy
# Check for valid indices
if 0 <= new_x < row and 0 <= new_y < col:
now_stack.append(img[new_x][new_y])
# Compute average and assign to result
result[r][c] = floor(sum(now_stack) / len(now_stack))
return result
This is a problem that is important to check some indexes that are out of index. If the index is out of index, there is no need to check that part and not possible neither. So i made a surrounding
list[tuple] to check the square, and if the new index is in row and col continued.
This process is not bad but not that good cause is not automatic and pythonic.
Dope solution
So after solve in my way, found whether there is some dope way to control the out of index
part. And guess this is the dopiest way.
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
rows, cols = len(img), len(img[0])
result = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
total_sum = 0
count = 0
for x in range(max(0, i-1), min(rows, i+2)):
for y in range(max(0, j-1), min(cols, j+2)):
total_sum += img[x][y]
count += 1
result[i][j] = total_sum // count
return result
`max(0, i-1), min(rows, i+2)` with this way, this solution controls that index never go out of limit of index. Sooooo dope bro.