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
hint1:Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0).
hint2:Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.
answer one
public int countSquares(int[][] A) {
int res = 0;
for (int i = 0; i < A.length; ++i) {
for (int j = 0; j < A[0].length; ++j) {
if (A[i][j] > 0 && i > 0 && j > 0) {
A[i][j] = Math.min(A[i - 1][j - 1], Math.min(A[i - 1][j], A[i][j - 1])) + 1;
}
res += A[i][j];
}
}
return res;
}
some clarity on the explanation:
‘A’ given matrix and ‘dp’ dynamic matrix we are building,
If A[i][j]=1 we claim dp[i][j] = min(dp[i-1],[j], dp[i][j-1], dp[i-1][j-1]) + 1
above holds true because,
Imagine you have a square of size k where (i,j) is in the right down corner of it.
Then dp[i-1][j] is at least of size k-1 (as a sub square) and the same is true for dp[i][j-1] and dp[i-1],[j-1]
therefore min(dp[i-1],[j], dp[i][j-1], dp[i-1][j-1]) is at least k-1.
// Given matrix
[
[1,0,1],
[1,1,0],
[1,1,0]
]
// DP matrix
we fill the first row and first column with zeros and a cell is zero if A[i][j] = 0 (as this can’t make a square matrix at all)
for A[i][j]>0 case we use the dp relation A[i][j] += min(A[i - 1][j - 1], min(A[i - 1][j], A[i][j - 1]));
0 0 0 0
0 1 0 1
0 1 1 0
0 1 2 0
hope this helps.
answer two
class Solution {
public int countSquares(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
int count = 0;
for(int i = 0; i < n; i++) if(matrix[i][0] == 1) dp[i][0] = 1;
for(int j = 0; j < m; j++) if(matrix[0][j] == 1) dp[0][j] = 1;
// dp[i][j] will tell you the max side of the square with bottom right corner at (i, j).
for(int i = 1; i < n; i++){
for(int j = 1; j < m; j++){
if(matrix[i][j] == 1){
int min = 1 + Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1]));
dp[i][j] = min;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++) count += dp[i][j];
}
return count;
}
}
answer three
answer four
更清晰的解释
参考