# Straightforward python solution

• ``````from copy import deepcopy as copy

class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
x_len = len(M)
y_len = len(M[0]) if x_len else 0
res = copy(M)
for x in range(x_len):
for y in range(y_len):
neighbors = [
M[_x][_y]
for _x in (x-1, x, x+1)
for _y in (y-1, y, y+1)
if 0 <= _x < x_len and 0 <= _y < y_len
]
res[x][y] = sum(neighbors) // len(neighbors)
return res
``````

• @niksite
I tried your code except that I used 'res=M' instead of 'res = copy(M)'. It failed the below test case. May I ask why it is so? Thanks.

Submission Result: Wrong Answer More Details
Input:
[[2,3,4],[5,6,7],[8,9,10],[11,12,13],[14,15,16]]
Output:
[[4,4,5],[6,6,6],[8,9,9],[11,11,12],[12,12,12]]
Expected:
[[4,4,5],[5,6,6],[8,9,9],[11,12,12],[13,13,14]]

• res = M is shallow copy
res[x][y] = sum(neighbors) // len(neighbors) will change neighbors of next M[_x][_y] in M.

• so great of a concise solution!

• @lan_yangyang Got it! Thank you so much.

• I was always looking for a concise way to go through the neighbor cells in the matrix.
Thank you very much for sharing!

• It seems that using deepcopy is slower than allocating a new 2-D list.

• The way of creating "neighbors" is awesome!

• from copy import deepcopy as copy

Renaming 'deepcopy' as 'copy' is bad practice.

• M[_x][_y]

Can anyone please explain why add '_' in front of the variables?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.