Given a 2D matrix and a target sum, count how many submatrices have elements that sum exactly to the target value.
A submatrix is defined by coordinates (x1, y1, x2, y2) representing all cells matrix[x][y] where x1 ≤ x ≤ x2 and y1 ≤ y ≤ y2. Two submatrices are considered different if they have any coordinate that differs.
Example: In matrix [[0,1,0],[1,1,1],[0,1,0]] with target 0, submatrices like [0] (single cell) and [[1,0],[1,0]] (2x2 region) both sum to target values and should be counted.
This is a challenging problem that combines prefix sums with hash table techniques to efficiently count valid rectangular regions in a 2D space.
Input & Output
Visualization
Time & Space Complexity
O(m²) to try all row pairs, O(n) to process each compressed array with hash table
Hash table stores at most n prefix sums, plus O(n) for compressed array
Constraints
- 1 ≤ matrix.length ≤ 100
- 1 ≤ matrix[0].length ≤ 100
- -1000 ≤ matrix[i][j] ≤ 1000
- -108 ≤ target ≤ 108
- All matrix elements and target fit in 32-bit integers