Problem: Find the Grid of Region Average

You are given a 0-indexed `m x n` grid `image` which represents a grayscale
image, where `image[i][j]` represents a pixel with intensity in the
range`[0..255]`. You are also given a non-negative integer `threshold`.

Two pixels `image[a][b]` and `image[c][d]` are said to be adjacent if `|a - c|
+ |b - d| == 1`.

A region is a `3 x 3` subgrid where the absolute difference in intensity
between any two adjacent pixels is less than or equal to `threshold`.

All pixels in a region belong to that region, note that a pixel can belong to
multiple regions.

You need to calculate a 0-indexed `m x n` grid `result`, where `result[i][j]`
is the average intensity of the region to which `image[i][j]` belongs, rounded
down to the nearest integer. If `image[i][j]` belongs to multiple regions,
`result[i][j]` is the average of the rounded down average intensities of these
regions, rounded down to the nearest integer. If `image[i][j]` does not belong
to any region, `result[i][j]` is equal to `image[i][j]`.

Return the grid `result`.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:
    m = len(image)
    n = len(image[0])
    sums = [[0] * n for _ in range(m)]
    counts = [[0] * n for _ in range(m)]

    for i in range(m - 2):
      for j in range(n - 2):
        if self._isRegion(image, i, j, threshold):
          subgridSum = sum(image[x][y] for x in range(i, i + 3) for y in range(j, j + 3))
          for x in range(i, i + 3):
            for y in range(j, j + 3):
              sums[x][y] += subgridSum // 9
              counts[x][y] += 1

    for i in range(m):
      for j in range(n):
        if counts[i][j] > 0:
          image[i][j] = sums[i][j] // counts[i][j]

    return image

  def _isRegion(self, image: List[List[int]], i: int, j: int, threshold: int) -> bool:
    for x in range(i, i + 3):
      for y in range(j, j + 3):
        if x > i and abs(image[x][y] - image[x - 1][y]) > threshold:
          return False
        if y > j and abs(image[x][y] - image[x][y - 1]) > threshold:
          return False
    return True


Java solution:
class Solution {
  public int[][] resultGrid(int[][] image, int threshold) {
    final int m = image.length;
    final int n = image[0].length;
    int[][] sums = new int[m][n];
    int[][] counts = new int[m][n];

    for (int i = 0; i < m - 2; ++i)
      for (int j = 0; j < n - 2; ++j)
        if (isRegion(image, i, j, threshold)) {
          final int subgridSum = getSubgridSum(image, i, j);
          for (int x = i; x < i + 3; ++x)
            for (int y = j; y < j + 3; ++y) {
              sums[x][y] += subgridSum / 9;
              counts[x][y] += 1;
            }
        }

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (counts[i][j] > 0)
          image[i][j] = sums[i][j] / counts[i][j];

    return image;
  }

  // Returns true if image[i..i + 2][j..j + 2] is a region.
  private boolean isRegion(int[][] image, int i, int j, int threshold) {
    for (int x = i; x < i + 3; ++x)
      for (int y = j; y < j + 3; ++y) {
        if (x > i && Math.abs(image[x][y] - image[x - 1][y]) > threshold)
          return false;
        if (y > j && Math.abs(image[x][y] - image[x][y - 1]) > threshold)
          return false;
      }
    return true;
  }

  // Returns the sum of image[i..i + 2][j..j + 2].
  private int getSubgridSum(int[][] image, int i, int j) {
    int subgridSum = 0;
    for (int x = i; x < i + 3; ++x)
      for (int y = j; y < j + 3; ++y)
        subgridSum += image[x][y];
    return subgridSum;
  }
}


C++ solution:
class Solution {
 public:
  vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {
    const int m = image.size();
    const int n = image[0].size();
    vector<vector<int>> sums(m, vector<int>(n));
    vector<vector<int>> counts(m, vector<int>(n));

    for (int i = 0; i < m - 2; ++i)
      for (int j = 0; j < n - 2; ++j)
        if (isRegion(image, i, j, threshold)) {
          const int subgridSum = getSubgridSum(image, i, j);
          for (int x = i; x < i + 3; ++x)
            for (int y = j; y < j + 3; ++y) {
              sums[x][y] += subgridSum / 9;
              counts[x][y] += 1;
            }
        }

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (counts[i][j] > 0)
          image[i][j] = sums[i][j] / counts[i][j];

    return image;
  }

 private:
  // Returns true if image[i..i + 2][j..j + 2] is a region.
  bool isRegion(const vector<vector<int>>& image, int i, int j, int threshold) {
    for (int x = i; x < i + 3; ++x)
      for (int y = j; y < j + 3; ++y) {
        if (x > i && abs(image[x][y] - image[x - 1][y]) > threshold)
          return false;
        if (y > j && abs(image[x][y] - image[x][y - 1]) > threshold)
          return false;
      }
    return true;
  }

  // Returns the sum of image[i..i + 2][j..j + 2].
  int getSubgridSum(const vector<vector<int>>& image, int i, int j) {
    int subgridSum = 0;
    for (int x = i; x < i + 3; ++x)
      for (int y = j; y < j + 3; ++y)
        subgridSum += image[x][y];
    return subgridSum;
  }
};