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) 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
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
res = M is shallow copy
res[x][y] = sum(neighbors) // len(neighbors) will change neighbors of next M[_x][_y] in M.
@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!
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.