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
题意: 给出一个有0或1组成矩阵,0表示空,1表示一个子矩阵,求这个矩阵中有多少个正方形的矩阵。
思路:与题221. Maximal Square 最大正方形类似,先求出矩阵中每个单位能与左、上、左上形成的最大矩形,然后根据边长长的矩形包含了边长短的矩形的原理,即可求出总共有多少正方形矩阵。
例如某个单位能与左、上、左上单位组成边长为3矩阵,那也能组成一个边长为2和一个边长为1的矩阵。
代码:
class Solution {
public int countSquares(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int[][] dp = new int[row+1][col+1];
int sum = 0;
for(int i=1;i<=row;i++){
for(int j=1;j<=col;j++){
if(matrix[i-1][j-1]==0)
continue;
//当前单位能与左、上、左上单位形成最大的正方形矩阵
dp[i][j]= Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1])) +1 ;
for(int k=dp[i][j];k>0;k--){
//边长长的矩阵也包含了边长更短的矩阵
sum+=1;
}
}
}
return sum;
}
}