Simplified Brute Force Solution | JAVA
Approach\n Describe your approach to solving the problem. \n1. First check whether the region is a valid region.\n2. Then simply calculate sum, and then average
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First check whether the region is a valid region.\n2. Then simply calculate sum, and then average of that region.\n3. Store all the average sums in result 2D array.\n4. Also store the count of how many times a cell was used in calculating average.\n5. Finally, to calculate average, divide res/count. \n\n# Code\n```\nclass Solution {\n    int dirX[] = {-1,0,1,0};\n    int dirY[] = {0,-1,0,1};\n    public int[][] resultGrid(int[][] image, int t) {\n        int m = image.length, n = image[0].length;\n        int[][] res = new int[m][n];\n        int[][] count = new int[m][n];\n        int sum = 0, avg = 0;\n        \n        for(int i=0; i<m; i++)\n        {\n            for(int j=0; j<n; j++)\n            {\n                if(i+3 > m || j+3 > n)\n                continue;\n                if(isRegion(image, i, j, t, m, n))\n                {\n                    // calculating average of a region\n                    // then adding it to res\n                    sum = 0;\n                    for(int p=i; p<i+3; p++)\n                    {\n                        for(int q=j; q<j+3; q++)\n                            sum += image[p][q];\n                    }\n                    avg = (sum/9); \n\n                    for(int p=i; p<i+3; p++)\n                    {\n                        for(int q=j; q<j+3; q++)\n                        {\n                            res[p][q] += avg;\n                            count[p][q]++;\n                        }\n                    }\n                }\n            }\n        }\n\n        // Storing final answer\n        for(int i=0; i<m; i++)\n        {\n            for(int j=0; j<n;j++)\n            {\n                if(count[i][j] == 0)\n                res[i][j] = image[i][j];\n                else\n                res[i][j] /= count[i][j];\n            }\n        }\n        return res;\n    }\n    \n    public boolean isRegion(int[][] image, int startRow, int startCol, int t, int m, int n)\n    {  \n        int nr=0, nc=0;\n        for(int i=startRow; i<startRow+3; i++)\n        {\n            for(int j=startCol; j<startCol+3; j++)\n            {\n                for(int k=0; k<4; k++)\n                {\n                    nr = i + dirX[k];\n                    nc = j + dirY[k];\n                    if(nr>=startRow && nr<startRow+3 && nc>=startCol && nc<startCol+3)\n                    {\n                        if(Math.abs(image[nr][nc] - image[i][j]) > t)\n                            return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n}\n```
['Matrix', 'Java']