1277. Count Square Submatrices with All Ones
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 <= 3001 <= arr[0].length <= 3000 <= arr[i][j] <= 1
class Solution {
public:
int m, n;
int recursiveCountSquares(int i, int j, vector<vector<int>>& matrix, vector<vector<int>>& t){
if(i>=m||j>=n)
return 0;
if(matrix[i][j]==0)
return 0;
if(t[i][j] != -1){
return t[i][j];
}
int right = recursiveCountSquares(i,j+1,matrix, t);
int diagonal = recursiveCountSquares(i+1,j+1, matrix, t);
int below = recursiveCountSquares(i+1,j, matrix, t);
return t[i][j] = 1 + min({right, diagonal, below});
}
int countSquares(vector<vector<int>>& matrix) {
m = matrix.size();
n = matrix[0].size();
int result = 0;
vector<vector<int>> t(m+1, vector<int>(n+1, -1));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==1){
result += recursiveCountSquares(i,j, matrix, t);
}
}
}
return result;
}
};
Complexity:
Space β O(m * n)
Time β O(m * n)