Straightforward python solution


  • 3
    N
    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
    

  • 0
    Z

    @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]]


  • 1
    L

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


  • 0
    L

    so great of a concise solution!


  • 0
    Z

    @lan_yangyang Got it! Thank you so much.


  • 0
    D

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


  • 0
    N

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


  • 0
    M

    The way of creating "neighbors" is awesome!


Log in to reply
 

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