Count Square Submatrices with All Ones in C++

C++Server Side ProgrammingProgramming

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 −

0111
1111
0111

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[0].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
raja
Published on 02-May-2020 15:35:01
Advertisements