Problem 999
Number of Submatrices That Sum to Target
Hard · 30 pts · Matrix, Hash Table, Prefix Sum
Problem
Count the non-empty submatrices (rectangular blocks of cells, counted by position) whose elements add up to TARGET. Fix a pair of rows top..bottom; the column sums between them form a one-dimensional array, and counting its subarrays with sum TARGET is the classic prefix-sum-and-hash-map problem. Over all row pairs this takes O(R² × C) time.
Input
The first line contains R, C and TARGET. Each of the next R lines contains C integers.
Output
Print the number of submatrices that sum to TARGET.
Constraints
1 <= R, C <= 100; -1000 <= values <= 1000; -10^8 <= TARGET <= 10^8
Example input
3 3 0 0 1 0 1 1 1 0 1 0
Example output
4
Explanation
In 0 1 0 / 1 1 1 / 0 1 0 with TARGET = 0, the four corner cells are the only blocks with sum 0. So the answer is 4.