Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
Constraints:
1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1
Solutions
Solution 1: Dynamic Programming
Thinking
We count all-\(1\) squares. \(m,n \le 300\), so enumerating squares is \(O(n^3)\). The largest square cornered at \((i,j)\) is limited by the squares at the top, left, and top-left cells.
\(f[i][j]\) is that side length: if the cell is \(1\), take the min of those three plus one. Each such square contributes \(f[i][j]\) squares (sides \(1\ldots f\)). DP turns counting into one fill.
We define \(f[i][j]\) as the side length of the square submatrix with \((i,j)\) as the bottom-right corner. Initially \(f[i][j] = 0\), and the answer is \(\sum_{i,j} f[i][j]\).
Consider how to perform state transition for \(f[i][j]\).
When \(\text{matrix}[i][j] = 0\), we have \(f[i][j] = 0\).
When \(\text{matrix}[i][j] = 1\), the value of state \(f[i][j]\) depends on the values of the three positions above, left, and top-left:
Time complexity \(O(m \times n)\), space complexity \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows and columns of the matrix respectively.