Count Submatrices With All Ones - Problem
Given an m x n binary matrix mat, return the number of submatrices that have all ones.
A submatrix is a contiguous rectangular region within a matrix. For example, in a 3x3 matrix, there are many possible submatrices of different sizes and positions.
Example: If the matrix is [[1,1,0],[1,1,0],[0,0,1]], we need to count all rectangular regions that contain only 1s.
Input & Output
Example 1 — Basic Matrix
$
Input:
mat = [[1,0,1],[1,1,0],[1,1,0]]
›
Output:
10
💡 Note:
Valid submatrices with all ones: 7 single-cell [1] submatrices at positions (0,0), (0,2), (1,0), (1,1), (2,0), (2,1); 2 vertical 2×1 submatrices at columns 0 and 1; 1 horizontal 1×2 submatrix at row 1; and 1 full 2×2 submatrix in the bottom-left corner
Example 2 — All Ones
$
Input:
mat = [[1,1],[1,1]]
›
Output:
9
💡 Note:
Four 1x1 submatrices, four 1x2 or 2x1 submatrices, and one 2x2 submatrix
Example 3 — All Zeros
$
Input:
mat = [[0,0],[0,0]]
›
Output:
0
💡 Note:
No submatrix contains all ones
Constraints
- 1 ≤ m, n ≤ 150
- mat[i][j] is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code