Count Submatrices With All Ones - Problem
Given an m x n binary matrix mat containing only 0s and 1s, your task is to count the total number of submatrices that contain all ones.
A submatrix is any rectangular region within the original matrix. This includes single cells, entire rows, entire columns, and any rectangular combination in between.
Example: In a 2x2 matrix with all ones, there are 9 possible submatrices: 4 individual cells, 2 horizontal rectangles, 2 vertical rectangles, and 1 full matrix - all containing only ones!
๐ฏ Goal: Return the count of all such submatrices efficiently.
Input & Output
example_1.py โ Basic 3x3 Matrix
$
Input:
mat = [[1,0,1],[1,1,0],[1,1,0]]
โบ
Output:
13
๐ก Note:
There are 13 submatrices with all ones: 6 of size 1x1, 4 of size 1x2, 2 of size 2x1, and 1 of size 2x2. The zeros break many potential larger rectangles.
example_2.py โ Small Square
$
Input:
mat = [[1,1],[1,1]]
โบ
Output:
9
๐ก Note:
A 2x2 matrix of all ones contains: 4 submatrices of size 1x1, 2 of size 1x2, 2 of size 2x1, and 1 of size 2x2. Total = 4+2+2+1 = 9.
example_3.py โ Single Row
$
Input:
mat = [[1,1,0,0]]
โบ
Output:
4
๐ก Note:
Only the first two consecutive 1s can form submatrices: two 1x1 submatrices, one 1x2 submatrix, plus the individual 1s again gives us 3 total submatrices containing all ones.
Visualization
Tap to expand
Understanding the Visualization
1
Build Heights
For each row, calculate height of consecutive 1s ending at each position
2
Create Histogram
Treat each row as a histogram with calculated heights
3
Count Rectangles
Use monotonic stack to count all rectangles in each histogram
4
Sum Results
Add up rectangle counts from all rows
Key Takeaway
๐ฏ Key Insight: Transform 2D matrix counting into 1D histogram problems - each row becomes a histogram where we count rectangles using monotonic stack technique!
Time & Space Complexity
Time Complexity
O(mยฒnยฒ)
For each cell, we may expand to create O(mn) submatrices in worst case
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค rows, cols โค 150
- mat[i][j] is either 0 or 1
- Matrix contains only binary values
- Submatrix must be rectangular (not arbitrary shape)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code