# Count Square Submatrices with All Ones in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we a binary matrix, of size m x n. We have to count number of square submatrices, with all 1s. So if the matrix is like −

 1 0 1 1 1 1 1 1 0 1 1 1

So there will be 15 squares. 10 squares of single ones, 4 squares of four ones, and 1 square with nine ones.

To solve this, we will follow these steps −

• set ans := 0, n := row count and m := column count
• for i in range 0 to m – 1
• ans := ans + matrix[n – 1, i]
• for i in range 0 to n – 1
• ans := ans + matrix[i, m – 1]
• ans := ans – matrix[n – 1, m - 1]
• for i in range n – 2 down to 0
• for j in range m – 2 down to 0
• if matrix[i, j] = 1, then
• matrix[i, j] := 1 + minimum of (matrix[i + 1, j + 1], matrix[i, j + 1], matrix[i + 1, j])
• otherwise matrix[i,j] := 0
• ans := ans + matrix[i, j]
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countSquares(vector<vector<int>>& matrix) {
int ans = 0;
int n = matrix.size();
int m = matrix.size();
for(int i = 0; i < m; i++)ans += matrix[n-1][i];
for(int i = 0; i < n; i++)ans += matrix[i][m-1];
ans -= matrix[n-1][m-1];
for(int i = n - 2;i >= 0; i--){
for(int j = m-2 ;j >= 0; j--){
matrix[i][j] = matrix[i][j] == 1? 1 + min({matrix[i+1][j+1],matrix[i] [j+1],matrix[i+1][j]}) : 0;
ans += matrix[i][j];
}
}
return ans;
}
};
main(){
vector<vector<int>> v = {{0,1,1,1},{1,1,1,1},{0,1,1,1}};
Solution ob;
cout << (ob.countSquares(v));
}

## Input

[[0,1,1,1],
[1,1,1,1],
[0,1,1,1]]

## Output

15