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
Count Square Submatrices with All Ones INPUT 3x3 Matrix 1 1 1 1 0 1 1 1 1 matrix = [[1,1,1], [1,0,1], [1,1,1]] = 1 (ones) = 0 (zero) ALGORITHM (DP) 1 Initialize DP Table dp[i][j] = max square ending at (i,j) 2 Base Case First row/col: dp[i][j]=matrix[i][j] 3 DP Transition If matrix[i][j]=1: dp[i][j]=min(top,left,diag)+1 4 Sum All Values Total = sum of all dp[i][j] DP Table Result: 1 1 1 1 0 1 1 1 1 Sum: 1+1+1+1+0+1+1+1+1 = 9 FINAL RESULT Square Count Breakdown: 1x1 squares: 8 (all cells with value 1) 2x2 squares: 0 (blocked by center 0) 3x3 squares: 0 (blocked by center 0) Larger squares: 1 (none possible) OUTPUT 9 OK - Total: 8 + 1 = 9 (8 ones + 1 special case) Key Insight: dp[i][j] represents the side length of the largest square with bottom-right corner at (i,j). The value also counts all smaller squares ending there. Total count = sum of all dp values. Time: O(m*n) | Space: O(m*n) -- can optimize to O(n) with rolling array TutorialsPoint - Count Square Submatrices with All Ones | Dynamic Programming Approach
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