Easy
Intuition\n Describe your first thoughts on how to solve this problem. \nbecause n can be 500 so we need to do in O(n^2) but we can have a large constant factor
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbecause n can be 500 so we need to do in O(n^2) but we can have a large constant factor\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThus we iterate to find all regions and then add sum to the answer of all regions where the elemnt can belong to \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> resultGrid(vector<vector<int>>& a, int t) {\n        int n = a.size() , m = a[0].size() ; \n        vector<vector<int>> b(n,  vector<int>(m, -1))  ; \n        for(int i = 0 ; i<n-2 ; i++)\n        {\n            for(int j = 0 ; j<m-2; j++)\n            {\n                bool fl = true ; \n                int su = 0 ;\n                for(int k = 0 ; k<3 ; k++)\n                {\n                    for(int l = 0 ; l<3; l++)\n                    {\n                        su += a[i+k][j+l] ; \n                        if(j+l+1<j+3 && abs(a[i+k][j+l] - a[i+k][j+l+1])>t)\n                        {\n                            fl = false ; \n                        }\n                        if(i+k+1<i+3 && abs(a[i+k][j+l] - a[i+k+1][j+l])>t)\n                        {\n                            fl = false ; \n                        }\n                    }\n                }\n                if(fl)\n                {\n                    b[i][j]  = su/9 ; \n                }\n            }\n        }\n\n        // return b ; \n        vector<vector<int>> c(n, vector<int>(m)) ; \n        for(int i = 0; i<n ; i++)\n        {\n            for(int j = 0 ; j<m ; j++)\n            {\n                int ans = 0 ; \n                int co = 0 ; \n                for(int k = -2 ; k<=0 ; k ++)\n                {\n                    for(int l = -2; l<=0 ; l++)\n                    {\n                        int x1 = i+k ;\n                        int y1 = j+l ;\n                        if(x1<n && x1>=0 && y1<m && y1>=0 && b[x1][y1]!=-1)\n                        {\n                            ans += b[x1][y1] ; \n                            co ++ ; \n                        }\n                    }\n                }\n                if(co>0)\n                {\n                    c[i][j] = ans/co ; \n                }\n                else\n                {\n                    c[i][j] = a[i][j] ; \n                }\n            }\n        }\n        return c; \n    }\n};\n```
['C++']