Count Square Submatrices with All Ones - Problem
Given a m × n matrix of ones and zeros, return how many square submatrices have all ones.
A square submatrix is a contiguous block of cells that forms a square shape (equal width and height). You need to count all possible squares of any size (1×1, 2×2, 3×3, etc.) where every cell in the square contains the value 1.
Input & Output
Example 1 — Basic 3×3 Matrix
$
Input:
matrix = [[1,1,1],[1,0,1],[1,1,1]]
›
Output:
8
💡 Note:
Count squares of all sizes: 8 squares of size 1×1 (at all positions where matrix[i][j]=1). No 2×2 or larger squares are possible due to the 0 at position (1,1) blocking all larger squares. Total = 8.
Example 2 — All Ones
$
Input:
matrix = [[1,1],[1,1]]
›
Output:
5
💡 Note:
4 squares of size 1×1 + 1 square of size 2×2 = 5 total squares
Example 3 — Single Row
$
Input:
matrix = [[1,0,1]]
›
Output:
2
💡 Note:
Only 1×1 squares possible: at positions (0,0) and (0,2) where value is 1
Constraints
- 1 ≤ matrix.length ≤ 300
- 1 ≤ matrix[0].length ≤ 300
- matrix[i][j] is 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code