Simple python solution for beginners
Here starting with r,c means first row and first col of a grid. eg for a 3*3 matrix r,c here will be 0,0.\n\nclass Solution:\n    def resultGrid(self, image: Li
Here starting with r,c means first row and first col of a grid. eg for a 3*3 matrix r,c here will be 0,0.\n```\nclass Solution:\n    def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]:\n        row,col=len(image),len(image[0])\n        newImg=[[0 for i in range(col)] for j in range(row)] #answer array\n        cnt=[[0 for i in range(col)] for j in range(row)] #no. of valid regions (i,j) is a part of.\n        directions=[[0,-1],[0,1],[1,0],[-1,0]] #to check adjacent cells\n        def check(r,c): #check if a 3*3 starting with r,c as (0,0) if its a region\n            for i in range(r,r+3):\n                for j in range(c,c+3):\n                    for x,y in directions:\n                        n_r,n_c=i+x,j+y\n                        if n_r<r or n_r>r+2 or n_c<c or n_c >c+2:#edge cases skipped\n                            continue\n                        if abs(image[i][j]-image[n_r][n_c])>threshold:\n                            return False\n            return True\n        def summ(r,c):#sum of the 3*3 starting with r,c\n            ans=0\n            for i in range(r,r+3):\n                for j in range(c,c+3):\n                    ans+=image[i][j]\n            return ans\n        def avg(r,c):#average of 3*3 starting with r,c\n            a=summ(r,c)//9\n            for i in range(r,r+3):\n                for j in range(c,c+3):\n                    newImg[i][j]+=a\n                    cnt[i][j]+=1\n        for i in range(2,row):\n            for j in range(2,col):\n                if check(i-2,j-2):\n                    avg(i-2,j-2)\n        for i in range(row):\n            for j in range(col):\n                if cnt[i][j]==0:   #means if (i,j) belonged to no region\n                    newImg[i][j]=image[i][j]\n                else:\n                    newImg[i][j]//=cnt[i][j] #getting the average of all the regions (i,j) belongs to\n        return newImg\n```
['Python']