Count how many square submatrices in a binary matrix contain only 1s.
Given an binary matrix, count the total number of square submatrices whose cells are all 1.
A square submatrix is a contiguous submatrix with equal height and width. Every square of every valid size should be counted separately.
Return the total count of such square submatrices.
You need to count all-ones squares of size , , , and so on, anywhere in the matrix.
matrix of size m x n, where each cell is 0 or 1.1s.1 <= m, n <= 300matrix[i][j] is either 0 or 11, its contribution depends on the neighboring subproblems above, left, and diagonally above-left.matrix: a 2D integer array containing only 0 and 1.Example 1
Input
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Output
15
Explanation
There are 10 squares of size 1x1, 4 squares of size 2x2, and 1 square of size 3x3, for a total of 15.
Example 2
Input
matrix = [[1,0,1],[1,1,0],[1,1,0]]
Output
7
Explanation
Count all square submatrices with only 1s. The total is 7.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.