[Python 🐍 ] MASK + AVG Grid -----> O ( M x N)
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n    def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:\n\n        M = len(image)\n        N = len(image[0])\n        \n        mask = [[1 for _ in range(N)] for j in range(M)]\n\n        avg = [[inf for _ in range(N)] for j in range(M)]\n        \n        res = [[inf for _ in range(N)] for j in range(M)]\n\n        dd = (0,0), (0,1), (1,0), (1,1), (0,-1), (-1,0), (-1,-1), (-1,1), (1,-1)\n\n        for x in range(1,M-1):\n            for y in range(1,N-1):\n\n                for a in range(x-1,x+2):\n                    for b in range(y-1,y+2):\n                        if a + 1 < x+2 and abs(image[a][b] - image[a+1][b]) > threshold:\n                            mask[x][y] = 0\n                            continue\n                        if b+1 < y+2 and abs(image[a][b] - image[a][b+1]) > threshold:\n                            mask[x][y] = 0\n                            continue\n                    if mask[x][y] == 0:\n                        continue\n\n        for i in range(1,M-1):\n\n            for j in range(1,N-1):\n                \n                if mask[i][j] == 0:\n                    continue\n\n                tot = 0\n\n                for dx, dy in dd:\n                    tot += image[i + dx][j + dy]\n                \n\n                avg[i][j] = floor(tot / 9)\n        \n\n        for i in range(M):\n\n            for j in range(N):\n\n                tot = 0\n                count = 0\n\n                for dx, dy in dd:\n                    if 0 <= i+dx < M and 0 <= j + dy < N and avg[i+dx][j+dy] != inf:\n                        tot += avg[i+dx][j+dy] \n                        count += 1\n                \n                if count == 0:\n                    res[i][j] = image[i][j]\n                else:\n                    res[i][j] = floor(tot / count)\n        \n        return res\n                \n                \n```
['Python3']