# Maximum size rectangle binary sub-matrix with all 1s in C++ Program

C++Server Side ProgrammingProgramming

In this problem, we are given a 2-D matrix bin[][] of size n*m that contains online binary numbers i.e. 0/1. Our task is to create a program to find the Maximum size rectangle binary sub-matrix with all 1s and Return the maximum area.

Let’s take an example to understand the problem,

## Input

bin[][] = {
{1, 0, 1, 1, 1}
{0, 1, 1, 1, 1}
{0, 0, 1, 1, 1}
{1, 1, 1, 1, 1}
}

## Output

12

## Explanation

For this rectangle the area with the maximum.

1, 1, 1
1, 1, 1
1, 1, 1
1, 1, 1

## Solution Approach

To solve the problem, we need to find the largest possible rectangular submatrix consisting of only 1’s. And for this, we need to find the maximum area till the current row is made by a rectangle.

The area till the current row will be calculated by first finding the number of consecutive ones till the current element in the column. And we will consider the elements with the same or greater number of once i.e. if all have different numbers, we will consider the smallest one. The row with the largest area so far will be the result

## Example

Live Demo

Program to illustrate the working of our solution,

#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 5
int calcAreaTillRow(int row[]){
stack<int> area1s;
int tos;
int maxArea = 0;
int curArea = 0;
int i = 0;
while (i < C) {
if (area1s.empty() || row[area1s.top()] <= row[i])
area1s.push(i++);
else {
tos = row[area1s.top()];
area1s.pop();
curArea = tos * i;
if (!area1s.empty())
curArea = tos * (i − area1s.top() − 1);
maxArea = max(curArea, maxArea);
}
}
while (!area1s.empty()) {
tos = row[area1s.top()];
area1s.pop();
curArea = tos * i;
if (!area1s.empty())
curArea = tos * (i − area1s.top() − 1);
maxArea = max(curArea, maxArea);
}
return maxArea;
}
int calcmaxRecSubMat1(int bin[][C]){
int result = calcAreaTillRow(bin);
for (int i = 1; i < R; i++) {
for (int j = 0; j < C; j++)
if (bin[i][j])
bin[i][j] += bin[i − 1][j];
result = max(result, calcAreaTillRow(bin[i]));
}
return result;
}
int main(){
int bin[][C] = {
{1, 0, 1, 1, 1},
{0, 1, 1, 1, 1},
{0, 0, 1, 1, 1},
{1, 1, 1, 1, 1}
};
cout<<"The area of maximum size rectangle binary sub−matrix with all 1s is "<<calcmaxRecSubMat1(bin);
return 0;
}

## Output

The area of maximum size rectangle binary sub-matrix with all 1s is 12