(Java) Simple solution with explanation.
Counting all sub-arrays with a given sum k for 1-Dimensional array can be used to reduce the time complexity.\n We fix the left and right columns one by one and
* Counting all sub-arrays with a given sum k for 1-Dimensional array can be used to reduce the time complexity.\n* We fix the left and right columns one by one and count sub-arrays for every left and right column pair.\n* The sum of elements in every row from left to right and store these sums in a temporary array say temp[].\n* So temp[i] indicates sum of elements from left to right in row i.\n* Count sub-arrays in temp[] having sum k.\n* Sum up all the counts for each temp[] with different left and right column pairs.\n```\npublic int numSubmatrixSumTarget(int[][] matrix, int target) {\n\n        int m = matrix.length;\n        int n = matrix[0].length;\n\n        int[] temp = new int[m];\n        int ans=0;\n        for (int left = 0;left<n;left++) {\n            Arrays.fill(temp,0);\n            for (int right=left;right<n;right++) {\n                for (int i=0;i<m;i++) {\n                    temp[i]+=matrix[i][right];\n                }\n                ans+= subCount(temp,target);\n            }\n        }\n        return ans;\n    }\n\n    private int subCount(int[] temp,int target) {\n        HashMap<Integer, Integer> prevSum = new HashMap<>();\n\n        int res = 0;\n        int currentSum = 0;\n\n        for (int t : temp) {\n\n            currentSum += t;\n            if (currentSum == target) {\n                res++;\n            }\n            if (prevSum.containsKey(currentSum - target)) {\n                res += prevSum.get(currentSum - target);\n            }\n            prevSum.merge(currentSum, 1, (a, b) -> a + b);\n        }\n\n        return res;\n    }\n```
[]