You are given an m x n integer matrix and an integer target. Return the number of non-empty submatrices whose elements add up to exactly target.
A submatrix is defined by a contiguous range of rows (x1 to x2) and a contiguous range of columns (y1 to y2), and it includes every cell whose row is in [x1, x2] and column is in [y1, y2]. Two submatrices are counted as different if they differ in any of these four boundary indices, even if their contents are identical.
Example 1
Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
There are four submatrices that sum to 0, each consisting of a single 0 cell at the four corners of the matrix.
Example 2
Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Five distinct submatrices sum to 0, including the full matrix and the four 1x2 or 2x1 bands that pair a 1 with a -1.
Constraints
1 <= matrix.length <= 1001 <= matrix[0].length <= 100-1000 <= matrix[i][j] <= 1000-10^8 <= target <= 10^8See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI