🎉 One-stop destination for all your technical interview Preparation 🎉
class Solution {
public:
int countSquares(vector<vector<int>>& matrix)
{
int n = matrix.size(), m = matrix[0].size();
vector<vector<int>> dp(n, vector<int>(m, 0));
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 || j == 0) { // fill first row and column as it is
dp[i][j] = matrix[i][j];
} else if (matrix[i][j] == 1) { // current element is 1, dp is min(top,left,lDigonal)+1
dp[i][j] = min(dp[i - 1][j], min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
} else {
dp[i][j] = 0; // current element is 0, so dp will be 0
}
ans += dp[i][j];
}
}
return ans;
}
};