Count Square Submatrices with All Ones

Given a binary matrix, return the total number of square submatrices that contain only 1s. Pattern focus: Grid path counting. Build the size of the largest square ending at each cell and accumulate the counts.

Input Format

grid contains only 0 and 1

Output Format

count of all-one square submatrices

Constraints

  • 1 <= rows, cols <= 300

Examples

Example 1:

Input:

grid = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]

Output:

15

Explanation:

There are 15 square submatrices containing only ones.

Example 2:

Input:

grid = [[1,0,1],[1,1,0],[1,1,0]]

Output:

7

Explanation:

This grid contains 7 all-one squares.

Example 3:

Input:

grid = [[1]]

Output:

1

Explanation:

A single one forms exactly one square.

Loading...
Count Square Submatrices with All Ones - Dp Grid