Hard problem
\n\nclass Solution {\n  public int[][] resultGrid(int[][] image, int threshold) {\n    final int m = image.length;\n    final int n = image[0].length;\n    int[
\n```\nclass Solution {\n  public int[][] resultGrid(int[][] image, int threshold) {\n    final int m = image.length;\n    final int n = image[0].length;\n    int[][] sums = new int[m][n];\n    int[][] counts = new int[m][n];\n\n    for (int i = 0; i < m - 2; ++i)\n      for (int j = 0; j < n - 2; ++j)\n        if (isRegion(image, i, j, threshold)) {\n          final int subgridSum = getSubgridSum(image, i, j);\n          for (int x = i; x < i + 3; ++x)\n            for (int y = j; y < j + 3; ++y) {\n              sums[x][y] += subgridSum / 9;\n              counts[x][y] += 1;\n            }\n        }\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (counts[i][j] > 0)\n          image[i][j] = sums[i][j] / counts[i][j];\n\n    return image;\n  }\n\n  // Returns true if image[i..i + 2][j..j + 2] is a region.\n  private boolean isRegion(int[][] image, int i, int j, int threshold) {\n    for (int x = i; x < i + 3; ++x)\n      for (int y = j; y < j + 3; ++y) {\n        if (x > i && Math.abs(image[x][y] - image[x - 1][y]) > threshold)\n          return false;\n        if (y > j && Math.abs(image[x][y] - image[x][y - 1]) > threshold)\n          return false;\n      }\n    return true;\n  }\n\n  // Returns the sum of image[i..i + 2][j..j + 2].\n  private int getSubgridSum(int[][] image, int i, int j) {\n    int subgridSum = 0;\n    for (int x = i; x < i + 3; ++x)\n      for (int y = j; y < j + 3; ++y)\n        subgridSum += image[x][y];\n    return subgridSum;\n  }\n}\n```
['Java']