KatInterview

Sum of All-One Squares in a Binary Grid

Dynamic ProgrammingAuto-graded · 18 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingmatrices2d-dp

Last 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 <= 300
  • matrix[i][j] is either 0 or 1

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.