1869 · Count Square Submatrices with All Ones
Algorithms
Medium
Description
Given a m * n matrix of ones and zeros, please count and return the number of square submatrix completely composed of 1.
1 <= arr.length <= 300
1 <= arr[0].length <= 300
Example
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.
Tags
Company
Google
Related Problems
1860
the Number of 0-submatrix
Hard
解法1:DP[i][j] 表示以(i,j)为右下角的正方形的边长。注意当我们得到一个DP[i][j] != 0时,我们实际上得到了DP[i][j]个新的正方形。比如DP[4][5]=3,那么我们得到了以(3,4)为右下角的,边长分别为1,2,3的三个新正方形,所以res+=3,而不是只加1。
另外,要注意(0,0)点的处理,因为它经历了第0行和第0边的两个循环,所以注意不要加两次!
class Solution {
public:
/**
* @param matrix: a matrix
* @return: return how many square submatrices have all ones
*/
int countSquares(vector<vector<int>> &matrix) {
int nRow = matrix.size();
if (nRow == 0) return 0;
int nCol = matrix[0].size();
vector<vector<int>> dp(nRow, vector<int>(nCol, 0));
int res = 0;
for (int i = 0; i < nRow; i++) {
if (matrix[i][0]) {
dp[i][0] = 1;
res++;
}
}
for (int i = 1; i < nCol; i++) {
//note matrix[0][0] cannot be counted twice!
if (matrix[0][i]) {
dp[0][i] = 1;
res++;
}
}
for (int i = 1; i < nRow; i++) {
for (int j = 1; j < nCol; j++) {
if (matrix[i][j] == 0) {
//dp[i][j] = 0;
continue;
}
dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
res += dp[i][j];
}
}
return res;
}
};