Python, Straightforward with Explanation


  • 1

    Say the matrix A has R rows and C columns.

    At some point (r, c), we look at all possible neighbors (nr, nc); there are size of them with sum value. A neighbor is actually in the matrix if 0 <= nr < R and 0 <= nc < C. We want the total sum value, divided (with integer division) by the number of neighbors.

    def imageSmoother(self, A):
        R, C = len(A), len(A[0])
        ans = [[0] * C for _ in A]
    
        for r in xrange(R):
            for c in xrange(C):
                value = size = 0
                for nr in (r-1, r, r+1):
                    for nc in (c-1, c, c+1):
                        if 0 <= nr < R and 0 <= nc < C:
                            value += A[nr][nc]
                            size += 1
                ans[r][c] = value // size
    
        return ans
    

Log in to reply
 

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