This will give u a clarity
Complexity\n\n- Time complexity:O(N * M * 81)\n- Space complexity:O(N * M)\n\n# Code\n\nclass Solution {\n    \npublic:\n    \n    int valid(int i,int j,vector<
# Complexity\n\n- Time complexity:O(N * M * 81)\n- Space complexity:O(N * M)\n\n# Code\n```\nclass Solution {\n    \npublic:\n    \n    int valid(int i,int j,vector<vector<int>>& image, int threshold){\n        \n            int r=image.size();\n            int c=image[0].size();\n            if(i+1>=r || i-1<0 || j+1>=c || j-1<0)\n            return -1;\n            \n            int top=i-1;\n            int down=i+1;\n            int left=j-1;\n            int right=j+1;\n            \n            int sum=0;\n\n            for(int r=-1;r<=1;r++){\n                for(int c=-1;c<=1;c++){\n                    sum+=image[i+r][j+c];\n                    int p=i+r;\n                    int q=j+c;\n                    \n                    if(p+1<=down && abs(image[p+1][q]-image[p][q])>threshold)\n                    return -1;\n                    if(q+1<=right && abs(image[p][q+1]-image[p][q])>threshold)\n                    return -1;\n                    if(p-1>=top && abs(image[p-1][q]-image[p][q])>threshold)\n                    return -1;\n                    if(q-1>=left && abs(image[p][q-1]-image[p][q])>threshold)\n                    return -1;   \n                }\n            }\n\n            return sum/9;    \n    }\n    \n    vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {\n        \n        int r=image.size();\n        int c=image[0].size();\n        \n        vector<vector<int>>ans(r,vector<int>(c,0));\n        \n        for(int i=0;i<r;i++){\n            for(int j=0;j<c;j++){\n\n                int value=0;\n                int count=0;\n\n                for(int di=-1;di<=1;di++){\n                    for(int dj=-1;dj<=1;dj++){\n                        if(i+di>=0 && i+di<r && j+dj>=0 && j+dj<c){\n                        int check=valid(i+di,j+dj,image,threshold);\n                        if(check!=-1){\n                            count++;\n                            value+=check;\n                        }\n                        }\n                    }\n                }\n                if(count==0)\n                ans[i][j]=image[i][j];\n                else{\n                    ans[i][j]=value/count;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n```
['C++']