Count how many square submatrices in a binary matrix contain only 1s.
Problem
Given an binary matrix, count the total number of square submatrices whose cells are all 1.
A square submatrix is a contiguous submatrix with equal height and width. Every square of every valid size should be counted separately.
Return the total count of such square submatrices.
Intuition
You need to count all-ones squares of size , , , and so on, anywhere in the matrix.
Input Format
- A binary matrix
matrixof sizem x n, where each cell is0or1.
Output Format
- Return an integer: the number of square submatrices consisting entirely of
1s.
Constraints
1 <= m, n <= 300matrix[i][j]is either0or1
Hints
- Think about the largest all-ones square that can end at each cell.
- If a cell is
1, its contribution depends on the neighboring subproblems above, left, and diagonally above-left.
Input Format
matrix: a 2D integer array containing only0and1.
Output Format
- Return the total number of all-ones square submatrices.
Constraints
- The matrix contains only binary values.
- The answer fits in a 32-bit signed integer for typical interview constraints.
Example 1
Input
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Output
15
Explanation
There are 10 squares of size 1x1, 4 squares of size 2x2, and 1 square of size 3x3, for a total of 15.
Example 2
Input
matrix = [[1,0,1],[1,1,0],[1,1,0]]
Output
7
Explanation
Count all square submatrices with only 1s. The total is 7.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.