Simple java code 75 ms
\n# Code\n\nclass Solution {\n\n\tpublic int[][] resultGrid(int[][] image, int threshold) {\n\t\tint[][] sum = new int[image.length][image[0].length], count = n
\n# Code\n```\nclass Solution {\n\n\tpublic int[][] resultGrid(int[][] image, int threshold) {\n\t\tint[][] sum = new int[image.length][image[0].length], count = new int[image.length][image[0].length];\n\t\tfor (int i = 2; i < image.length; i++) {\n\t\t\tfor (int j = 2, curr; j < image[0].length; j++) {\n\t\t\t\tif ((curr = resultGrid(i, j, image, threshold)) >= 0) {\n\t\t\t\t\tfor (int x = i - 2; x <= i; x++) {\n\t\t\t\t\t\tfor (int y = j - 2; y <= j; y++) {\n\t\t\t\t\t\t\tsum[x][y] += curr;\n\t\t\t\t\t\t\tcount[x][y]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < image.length; i++) {\n\t\t\tfor (int j = 0; j < image[0].length; j++) {\n\t\t\t\timage[i][j] = count[i][j] > 0 ? sum[i][j] / count[i][j] : image[i][j];\n\t\t\t}\n\t\t}\n\t\treturn image;\n\t}\n\n\tprivate int resultGrid(int i, int j, int[][] image, int threshold) {\n\t\tint sum = 0;\n\t\tfor (int x = i - 2; x <= i; x++) {\n\t\t\tfor (int y = j - 2; y <= j; y++) {\n\t\t\t\tif (x < i && Math.abs(image[x][y] - image[x + 1][y]) > threshold\n\t\t\t\t\t\t|| y < j && Math.abs(image[x][y] - image[x][y + 1]) > threshold) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tsum += image[x][y];\n\t\t\t}\n\t\t}\n\t\treturn sum / 9;\n\t}\n}\n```
['Array', 'Matrix', 'Java']