Maximal Square in C++


Suppose we have a 2D binary matrix filled with 0's and 1's. We have to find the largest square containing only 1's and return its area. So if the matrix is like −

10100
10110
11111
10010

Then the output will be 4

To solve this, we will follow these steps −

  • ans := 0, n := number of rows, c := number of rows

  • if n is 0, then return 0

  • Create another matrix of order (n x c)

  • for i in range 0 to n – 1

    • for j in range 0 to c – 1

      • m[i, j] := matrix[i, j]

      • ans := maximum of m[i, j] and ans

  • for j in range 0 to c – 1

    • if m[i, j] is not 0, then

      • m[i, j] := 1 + minimum of m[i + 1, j], m[i, j-1], m[i + 1, j-1],

    • ans := maximum of m[i, j] and ans

  • return ans*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 maximalSquare(vector<vector<char>>& matrix) {
      int ans = 0;
      int n = matrix.size();
      if(!n)return 0;
      int c = matrix[0].size();
      vector<vector<int>> m(n, vector <int> (c));
      for(int i =0;i<n;i++){
         for(int j = 0; j<c;j++){
            m[i][j] = matrix[i][j] - '0';
            ans = max(m[i][j],ans);
         }
      }
      for(int i =n-2;i>=0;i--){
         for(int j =1;j<c;j++){
            if(m[i][j]){
               m[i][j] = 1 + min({m[i+1][j],m[i][j-1],m[i+1][j-1]});
            }
            ans = max(ans,m[i][j]);
         }
      }
      return ans*ans;
   }
};
main(){
   vector<vector<char>> v = {{'1','0','1','0','0'},{'1','0','1','1','1'},{'1','1','1','1','1'},         {'1','0','0','1','0'}};
   Solution ob;
   cout << ((ob.maximalSquare(v)));
}

Input

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

Output

4

Updated on: 30-Apr-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements