Problem Description
Given a matrix and an integer target, count the number of non-empty submatrices whose elements sum exactly to target. A submatrix is defined by the coordinates (x1, y1, x2, y2) covering all cells matrix[x][y] for x1 ≤ x ≤ x2 and y1 ≤ y ≤ y2.
Key Insights
- Transform the 2D submatrix sum problem into multiple 1D subarray sum problems.
- Precompute cumulative sums by fixing two row boundaries and then summing columns between these rows.
- Use a hash table (or dictionary) to count the number of subarrays with a given sum, reducing the problem to the classic "subarray sum equals k" question.
- Iterate over all possible row pairs and for each, treat the column sums as an array where the target sum is sought.
Space and Time Complexity
Time Complexity: O(n² * m), where n is the number of rows and m is the number of columns. Space Complexity: O(m), used by the hash table for storing cumulative sums along the columns.
Solution
The idea is to iterate over all pairs of rows (top and bottom) and, for each pair, compute the cumulative column sums between these rows. This converts the problem into finding the number of subarrays in a one-dimensional array (the column sums) that add up to the target. For each such 1D problem, use a hash table to track the frequency of cumulative sums seen so far and count how many times the difference (current sum - target) has been seen. This count gives the number of subarrays ending at the current index which sum to target. Combining counts from all possible row pairs yields the final result.