C++ Solution
Code\n\nclass Solution {\n    vector<pair<int,int>> dir = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };\npublic:\n    vector<vector<int>> resultGrid(vector<vector<int>>
# Code\n```\nclass Solution {\n    vector<pair<int,int>> dir = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };\npublic:\n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        \n        int m = image.size(), n = image[0].size();\n        \n        vector<vector<pair<int,int>>> v(m, vector<pair<int,int>> (n, {0, 0})); // count -> sum (avg)\n        \n        for(int i=1; i<m-1; i++) {\n            for(int j=1; j<n-1; j++) {\n                \n                int sum = 0;\n                \n                bool region = true;\n                \n                for(int x=i-1; x<=i+1; x++) {\n                    for(int y=j-1; y<=j+1; y++) {\n                        \n                        for(int d=0; d<4; d++) {\n                            int a = x + dir[d].first;\n                            int b = y + dir[d].second;\n                            \n                            if(a < 0 || b < 0 || a >= m || b >= n) continue;\n                            if(abs(a - i) > 1 || abs(b - j) > 1) continue;\n                            \n                            if(abs(image[x][y] - image[a][b]) > threshold) {\n                                // cout << i << j << " " << x << y << " " << a << b << endl;\n                                region = false;\n                                break;\n                            }\n                        }\n                        \n                        if(!region) break;\n                    }\n                    if(!region) break;\n                }\n                \n                if(!region) continue;\n                \n                for(int x=i-1; x<=i+1; x++) {\n                    for(int y=j-1; y<=j+1; y++) { \n                        sum += image[x][y];\n                    }\n                }\n                \n                int avg = sum / 9;\n                \n                for(int x=i-1; x<=i+1; x++) {\n                    for(int y=j-1; y<=j+1; y++) { \n                        v[x][y].first += 1;\n                        v[x][y].second += avg;\n                    }\n                }\n            }\n        }\n        \n        for(int i=0; i<m; i++) {\n            for(int j=0; j<n; j++)  {\n                if(v[i][j].first != 0) {\n                    image[i][j] = v[i][j].second / v[i][j].first;\n                }\n            }\n        }\n        \n        return image;\n    }\n};\n```
['C++']