- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 48 lines of Java from the credited upstream file 3030.java.
- The implementation visibly relies on sequence storage.
- 10 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[][] resultGrid(int[][] image, int threshold) {3 final int m = image.length;4 final int n = image[0].length;5 int[][] sums = new int[m][n];6 int[][] counts = new int[m][n];7 8 for (int i = 0; i < m - 2; ++i)9 for (int j = 0; j < n - 2; ++j)10 if (isRegion(image, i, j, threshold)) {11 final int subgridSum = getSubgridSum(image, i, j);12 for (int x = i; x < i + 3; ++x)13 for (int y = j; y < j + 3; ++y) {14 sums[x][y] += subgridSum / 9;15 counts[x][y] += 1;16 }17 }18 19 for (int i = 0; i < m; ++i)20 for (int j = 0; j < n; ++j)21 if (counts[i][j] > 0)22 image[i][j] = sums[i][j] / counts[i][j];23 24 return image;25 }26 27 28 private boolean isRegion(int[][] image, int i, int j, int threshold) {29 for (int x = i; x < i + 3; ++x)30 for (int y = j; y < j + 3; ++y) {31 if (x > i && Math.abs(image[x][y] - image[x - 1][y]) > threshold)32 return false;33 if (y > j && Math.abs(image[x][y] - image[x][y - 1]) > threshold)34 return false;35 }36 return true;37 }38 39 40 private int getSubgridSum(int[][] image, int i, int j) {41 int subgridSum = 0;42 for (int x = i; x < i + 3; ++x)43 for (int y = j; y < j + 3; ++y)44 subgridSum += image[x][y];45 return subgridSum;46 }47}48