[C++] Find Regions First
Code\n\nclass Solution {\npublic:\n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        int m = image.size();\n        int n
# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        int m = image.size();\n        int n = image[0].size();\n        vector<vector<int>> region(m, vector<int>(n, -1));\n        for (int i = 1; i < m - 1; i++) {\n            for (int j = 1; j < n - 1; j++) {\n                region[i][j] = region_average(i, j, image, threshold);\n            }\n        }\n        vector<vector<int>> result(m, vector<int>(n));\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                int count = 0;\n                int sum = 0;\n                for (int k = i - 1; k <= i + 1; k++) {\n                    if (k >= 0 && k < m) {\n                        for (int l = j - 1; l <= j + 1; l++) {\n                            if (l >= 0 && l < n) {\n                                if (region[k][l] != -1) {\n                                    sum += region[k][l];\n                                    count++;\n                                }\n                            }\n                        }\n                    }\n                }\n                if (count == 0) {\n                    result[i][j] = image[i][j];\n                } else {\n                    result[i][j] = sum / count;\n                }\n            }\n        }\n        return result;\n    }\n\nprivate:\n    int region_average(int i, int j, vector<vector<int>>& grid, int threshold) {\n        int sum = 0;\n        for (int k = i - 1; k <= i + 1; k++) {\n            for (int l = j - 1; l <= j + 1; l++) {\n                sum += grid[k][l];\n            }\n        }\n        for (int k = i - 1; k <= i + 1; k++) {\n            if (abs(grid[k][j - 1] - grid[k][j]) > threshold ||\n                abs(grid[k][j] - grid[k][j + 1]) > threshold) {\n                return -1;\n            }\n        }\n        for (int l = j - 1; l <= j + 1; l++) {\n            if (abs(grid[i - 1][l] - grid[i][l]) > threshold ||\n                abs(grid[i][l] - grid[i + 1][l]) > threshold) {\n                return -1;\n            }\n        }\n        return sum / 9;\n    }\n};\n```
['Array', 'Matrix', 'C++']