Python Medium
\nclass Solution:\n    def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:\n        M, N = len(image), len(image[0])\n        \n   
```\nclass Solution:\n    def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:\n        M, N = len(image), len(image[0])\n        \n        count = [[0] * N for _ in range(M)]\n        \n        arr = [[0] * N for _ in range(M)]\n        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n        for i in range(M):\n            for j in range(N):\n                if i + 2 < M and j + 2 < N:\n                    \n                            \n                    check = True\n                    \n                    for ii in range(3):\n                        for jj in range(3):\n                            \n                            for dx, dy in directions:\n                                nx, ny = i + ii + dx, j + jj + dy\n                                \n                                \n                                if not (0 <= nx < M) or not (0 <= ny < N):\n                                    continue\n                                    \n                                if nx >= i + 3 or ny >= j + 3:\n                                    continue\n                                    \n                                if nx < i or ny < j:\n                                    continue\n\n                                if abs(image[i + ii][j + jj] - image[nx][ny]) > threshold:\n                                    check = False\n                                    break\n                    \n                    if not check: \n                        # print(i, j, image)\n                        continue\n                        \n                        \n                    total = 0\n                    for ii in range(3):\n                        for jj in range(3):\n                            total += image[i + ii][j + jj]\n                        \n                    for ii in range(3):\n                        for jj in range(3):\n                            arr[i + ii][j + jj] += total // 9\n                    \n                    \n                    for ii in range(3):\n                        for jj in range(3):\n                            count[i + ii][j + jj] += 1\n                    \n        \n        res = image.copy()\n      \n        \n        for i in range(M):\n            for j in range(N):\n                if count[i][j] == 0:\n                    continue\n                    \n                res[i][j] = arr[i][j] // count[i][j]\n\n        return res\n        \n                    \n                    \n        \n```
['Python3']