This solution is easy to extend for different surrounding cells via changing the offset list. E.g, offset = [-2, -1, 0, 1, -2] for surrounding 5x5 cells.
Please note that using
r = [ * m for x in range(n)]
r = [ * m] * n
for 2d array initiation. See StackOverflow for more explanation.
class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ n = len(M) # rows m = len(M) # columns # r = [ * m] * n # https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly r = [ * m for x in range(n)] offset = [-1, 0, 1] cells = [(x, y) for x in offset for y in offset] for i in range(0, n): for j in range(0, m): s, c = 0, 0 for x, y in cells: if -1 < i + x < n and -1 < j + y < m: s += M[i+x][j+y] c += 1 r[i][j] = int(s / c) return r