Straightforward python 10-line solution, using O(nm) time O(nm) space


  • 0
    P
    def imageSmoother(self, M):
        """
        :type M: List[List[int]]
        :rtype: List[List[int]]
        """
        res = [ [0]*len(M[0]) for _ in range(len(M)) ]
        for i in range(len(M)):
            for j in range(len(M[0])):
                surroundingcells = [ (_i,_j) for _i in (i-1,i,i+1) for _j in (j-1,j,j+1) ]
                value, count = 0,0
                for ti,tj in surroundingcells:
                    if 0 <= ti < len(M) and 0 <= tj < len(M[0]):
                        value, count = value + M[ti][tj], count + 1
                res[i][j] = value // count 
    
        return res
    

    Pretty straightforward, [ [0]*len(M[0]) for _ in range(len(M)) ] generates an array with the same dimensions as M filled with zeros. Then iterate over all points in the array. For each point, [ (_i,_j) for _i in (i-1,i,i+1) for _j in (j-1,j,j+1) ] generates all 8 surrounding cells and itself. Check each surrounding point, if it is not out of bounds, add it to our sum. Compute the average and set it in the result array.


Log in to reply
 

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