Simple C++ Solution
\n\nclass Solution {\npublic:\n    bool check(int p1, int p2, vector<vector<int>>& image, int t){\n        vector<int> r1={0, 0, -1, 1}, c1={1, -1, 0, 0};\n    
```\n\nclass Solution {\npublic:\n    bool check(int p1, int p2, vector<vector<int>>& image, int t){\n        vector<int> r1={0, 0, -1, 1}, c1={1, -1, 0, 0};\n        for(int i=p1-1; i<=p1+1; i++){\n            for(int j=p2-1; j<=p2+1; j++){\n                for(int k=0; k<4; k++){\n                    int v1=i+r1[k], v2=j+c1[k];\n                    if(v1>=0 && v2>=0 && v1<image.size() && v2<image[0].size() && v1>=p1-1 && v1<=p1+1 && v2>=p2-1 && v2<=p2+1){\n                        \n                        if(abs(image[i][j] - image[v1][v2])>t) {\n                            return false;\n                        }\n                    }\n                }\n            }\n        }\n        return true;\n    }\n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        \n        int m=image.size(), n=image[0].size();\n        vector<vector<int>> vis(m, vector<int>(n, -1)), ans=vis;\n        for(int i=1; i<m-1; i++){\n            for(int j=1; j<n-1; j++){\n                bool chk = check(i, j, image, threshold);\n                if(chk){\n                    int avg=0;\n                    for(int p1=i-1; p1<=i+1; p1++){\n                        for(int p2=j-1; p2<=j+1; p2++){\n                            avg += image[p1][p2];\n                        }\n                    }\n                    avg /= 9;\n                    vis[i][j] = avg;\n                }\n            }\n        }\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                int ans1=0, cnt=0;\n                for(int p1=i-1; p1<=i+1; p1++){\n                    for(int p2=j-1; p2<=j+1; p2++){\n                        if(p1>=0 && p1<m && p2>=0 && p2<n && vis[p1][p2]!=-1) {\n                            ans1 += vis[p1][p2];\n                            cnt++;\n                        }\n                    }\n                }\n                if(cnt==0) ans[i][j] = image[i][j];\n                else ans[i][j] = ans1/cnt;\n            }\n        }\n        return ans;\n    }\n};\n```
['C', 'C++']