LC 0661 [E] Image Smoother - ALawliet/algorithms GitHub Wiki

class Solution:
    def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:
        directions = ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (-1, 1), (1, -1))
        if not M:
            return M
        len_cols = len(M[0])
        len_rows = len(M)
        result = [[0]*len_cols for _ in range(len_rows)]
        for i in range(len_rows):
            for j in range(len_cols):
                total = 0
                count = 0
                for x, y in directions:
                    new_x = x+i
                    new_y = y+j
                    if 0<=new_x<len_rows and 0<=new_y<len_cols:
                        total += M[new_x][new_y]
                        count += 1
                result[i][j] = total//count
        return result