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: 9
💡 Note: Count squares of all sizes: 6 squares of size 1×1, 2 squares of size 2×2, and 1 square of size 3×3 (but blocked by the 0). Total = 6 + 2 + 0 = 8. Wait, let me recalculate: 1×1 squares at positions where matrix[i][j]=1 gives us 8 squares. 2×2 squares: top-left corners at (0,0) and (0,1) both fail due to the 0 at (1,1). Actually, only 1×1 squares work, so 8 total.
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
Count Square Submatrices with All OnesInput Matrix1111Valid Squares Found1×14 squares1 square of size 2×2ResultTotal: 54 + 1 = 5Matrix [[1,1],[1,1]] contains:• 4 squares of size 1×1• 1 square of size 2×2Answer: 5 total square submatrices
Understanding the Visualization
1
Input Matrix
2D matrix with 0s and 1s
2
Find Squares
Identify all square regions with only 1s
3
Count Total
Sum squares of all sizes: 1×1, 2×2, 3×3, etc.
Key Takeaway
🎯 Key Insight: Use DP where dp[i][j] = size of largest square ending at (i,j), then sum all dp values
Asked in
Google 45 Amazon 38 Microsoft 32
52.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen