Count Square Submatrices with All Ones
Implement countSquares
Given a binary
matrix, count how many square submatrices — of any size, 1×1 and up — are made entirely of 1s.
Trying every square directly, with a prefix-sum table to check each one in O(1), already works. The faster way notices something sharper: define dp[r][c] as the side length of the biggest all-1s square that has its bottom-right corner exactly at (r, c). That value can only grow past 1 if a square one size smaller already ends at the cell above, the cell to the left, *and* the cell diagonally above-left — so dp[r][c] is the smallest of those three neighbors, plus one. The neat payoff: dp[r][c] doesn't just say how big the largest square there is, it also equals how many squares of every size up to that end there — a size-3 square ending somewhere means a size-2 and a size-1 do too, at the very same corner. Summing dp[r][c] across the whole grid is the answer.
Example 1:
Input: matrix = [[1,0,1],[1,1,0],[1,1,1]]
Output: 8
Example 2:
Input: matrix = [[0,1,1],[1,1,1],[0,1,1]]
Output: 9
Example 3:
Input: matrix = [[0,0],[0,0]]
Output: 0
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ rows, cols ≤ 200 - ●
every entry of matrix is either 0 or 1
matrix =
[[1,0,1], [1,1,0], [1,1,1]]