Sum of All-One Squares in a Binary Grid
Dynamic ProgrammingAuto-graded · 18 test casesLast updated
Tests dynamic programming on 2D grids by computing the total count of square submatrices containing only ones.
You are given a binary matrix matrix with dimensions m × n, where every element is either 0 or 1.
Your task is to determine how many square submatrices exist that contain only 1s.
A square submatrix is defined by its top-left corner at position (r1, c1) and its bottom-right corner at (r2, c2), where the side length satisfies r2 - r1 == c2 - c1.
Write a function that returns the total number of such squares.
Constraints
1 <= m, n <= 300matrix[i][j]is either0or1
Examples
Example 1
Input: count_all_one_squares([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]])
Output: 15
Example 2
Input: count_all_one_squares([[1, 0, 1], [1, 1, 0], [1, 1, 0]])
Output: 7
Hints
Hint 1
Consider how many squares have their bottom-right corner at each cell—this avoids double-counting.
Hint 2
For a cell containing 1, the number of squares ending there depends on the largest square you can form, which relates to neighboring cells.
Hint 3
Use dynamic programming: if dp[r][c] represents the side length of the largest all-one square ending at (r,c), then that cell contributes dp[r][c] squares to the total.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to count squares by their bottom-right corner. Every square has exactly one bottom-right cell, so if we determine how many all-one squares end at each cell, summing across all cells gives the answer.
We define dp[r][c] as the side length of the largest all-one square whose bottom-right corner is at position (r, c). If this largest square has side length k, then there are exactly k valid squares ending at that cell: squares of size 1×1, 2×2, ..., k×k. Each smaller square is contained within the largest one, sharing the same bottom-right corner.
The recurrence relation is:
- If
matrix[r][c] == 0, thendp[r][c] = 0(no square can end here) - If
matrix[r][c] == 1, thendp[r][c] = 1 + min(dp[r-1][c], dp[r][c-1], dp[r-1][c-1])
Out-of-bounds positions are treated as 0.
Why This Works
When matrix[r][c] == 1, a square of side k ≥ 2 ending at (r, c) is all ones if and only if three smaller squares are also all ones:
- The square of side
k-1ending at(r-1, c)(above) - The square of side
k-1ending at(r, c-1)(left) - The square of side
k-1ending at(r-1, c-1)(diagonal)
These three regions, together with the current cell, completely cover the k × k square. The largest feasible side length is therefore 1 + min(above, left, diagonal).
Space-Optimized Implementation
We use a rolling 1D array of size cols + 1 instead of a full 2D table. Index 0 serves as a sentinel (always 0), eliminating special cases for the left boundary. As we process each cell:
dp[j]holds the value from the previous row (above)dp[j-1]holds the value just computed in the current row (left)diagonaltracks the saved value from the previous row and column
We save the old dp[j] value before updating it, then use that saved value as the diagonal for the next column.
from typing import List
def count_all_one_squares(matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
dp = [0] * (cols + 1)
total = 0
for row in matrix:
diagonal = 0
for j in range(1, cols + 1):
above = dp[j]
if row[j - 1] == 1:
dp[j] = 1 + min(dp[j], dp[j - 1], diagonal)
total += dp[j]
else:
dp[j] = 0
diagonal = above
return total
Complexity
Time: O(m · n)
We process each cell exactly once with constant-time operations.
Space: O(n)
We maintain a single auxiliary array of length cols + 1. A naive 2D DP table would require O(m · n) space.