# Find if there is a rectangle in binary matrix with corners as 1 in C++

Suppose we have a binary matrix. We have to find if there is any rectangle or sequence in the given matrix whose all four corners are equal to 1. The matrix is like

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

The result will be yes. Here one rectangle is present, whose corners are with 1s.

 1 0 1 0 1 0 1 0 1

To solve this we will use one efficient approach. We will follow these steps −

• Scan the matrix from top to bottom line by line

• For each line remember each combination of two 1’s and push that into a hash-set.

• If we ever find that combination again in the later line, we will get our rectangle.

## Example

Live Demo

#include<iostream>
#include<unordered_set>
#include<unordered_map>
#include<vector>
using namespace std;
bool isRectanglePresent(const vector<vector<int> >& matrix) {
int rows = matrix.size();
if (rows == 0)
return false;
int columns = matrix.size();
unordered_map<int, unordered_set<int> > table;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns - 1; ++j) {
for (int k = j + 1; k < columns; ++k) {
if (matrix[i][j] == 1 && matrix[i][k] == 1) {
if (table.find(j) != table.end() && table[j].find(k) != table[j].end())
return true;
if (table.find(k) != table.end() && table[k].find(j) != table[k].end())
return true;
table[j].insert(k);
table[k].insert(j);
}
}
}
}
return false;
}
int main() {
vector<vector<int> > matrix = {
{ 1, 0, 0, 1, 0 },
{ 0, 0, 1, 0, 1 },
{ 0, 0, 0, 1, 0 },
{ 1, 0, 1, 0, 1 }
};
if (isRectanglePresent(matrix))
cout << "Rectangle is present";
else
cout << "Rectangle is not present";
}

### Output

Rectangle is present

Updated on: 03-Jan-2020

115 Views 