[JAVA] Easy to Understand | Heavily Commented | Detailed Explanation with Pictures
Region(Answer)\n\nSo we first need the sum from each of the following regions:\n1. Region(A)\n\t\n2. Region(B)\n\t\n3. Region(C)\n   \n4. Region(D)\n   \nRegion
Region(Answer)\n![image](https://assets.leetcode.com/users/images/d00849a5-cb20-4edc-aead-5a6a459a9d13_1658113975.539614.png)\nSo we first need the sum from each of the following regions:\n1. Region(A)\n\t![image](https://assets.leetcode.com/users/images/ec4d1b9e-b2fb-414f-a710-6edab00ee3b7_1658113980.4055543.png)\n2. Region(B)\n\t![image](https://assets.leetcode.com/users/images/e9c0952f-4c70-4d2c-b051-3ce1ada0d650_1658113989.4605181.png)\n3. Region(C)\n   ![image](https://assets.leetcode.com/users/images/add5a19c-d4df-494a-8f1a-003700980546_1658113998.129529.png)\n4. Region(D)\n   ![image](https://assets.leetcode.com/users/images/3ce884fc-fb99-4907-a1aa-3a341394a064_1658114008.1346068.png)\nRegion(Answer) = Region(A) - Region(B) - Region(C) + Region(D)\n```\nclass Solution {\n    public int numSubmatrixSumTarget(int[][] matrix, int target) {\n        int m = matrix.length;\n        int n = matrix[0].length;\n        \n\t\t// aux[i][j] is the sum of sub-matrix which start at [0][0] and end in [i][j]\n        int[][] aux = new int[m + 1][n + 1]; // padding on top and left\n        for (int i = 1; i < m + 1; i++) {\n            for (int j = 1; j < n + 1; j++) {\n\t\t\t\t// draw a picture, you will understand it easily~\n                aux[i][j] = matrix[i - 1][j - 1] + aux[i - 1][j] + aux[i][j - 1] - aux[i - 1][j - 1]; \n            }\n        }\n        \n        int res = 0;\n\t\t// try each sub-matrix\n        for (int x1 = 1; x1 < m + 1; x1++) {\n            for (int y1 = 1; y1 < n + 1; y1++) {\n                for (int x2 = x1; x2 < m + 1; x2++) {\n                    for (int y2 = y1; y2 < n + 1; y2++) {\n                        if (target == aux[x2][y2] - aux[x2][y1 - 1] - aux[x1 - 1][y2] + aux[x1 - 1][y1 - 1])\n                            res++;\n                    }\n                }\n            }\n        }\n        \n        return res;\n    }\n}\n```\nPlease vote if it helps\uD83D\uDE06~
[]