[Python] Clean and Accepted Solution


  • 0
    N

    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 = [[0] * m for x in range(n)]

    instead of
    r = [[0] * 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[0])   # columns
            # r = [[0] * m] * n 
            # https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
            r = [[0] * 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
            
    

Log in to reply
 

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