Find size of the largest ‘+’ formed by all ones in a binary matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an NxN binary matrix bin[][]. Our task is to find the size of the largest ‘+’ formed by all ones in a binary matrix.

Let’s take an example to understand the problem,

Input

0 1 1
1 1 1
0 1 0

Output

5

Solution Approach

A simple solution to the problem is to find the largest ‘+’ for which we need to find the maximum number of 1’s in one direction for a point in the matrix which needs to be the same in all four directions for a given 1. For this, we will create one matrix for each side of the point i.e. 4. Each will store the number of consecutive 1’s for the given element. For all index values, we will find the maximum value which is the minimum of all consecutive ones in all four directions.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
#define N 7
int findLargestPlusSize(int mat[N][N]) {
   int conOneLeft[N][N], conOneRight[N][N], conOneTop[N][N], conOneBottom[N][N];
   for (int i = 0; i < N; i++) {
      conOneTop[0][i] = mat[0][i];
      conOneBottom[N - 1][i] = mat[N - 1][i];
      conOneLeft[i][0] = mat[i][0];
      conOneRight[i][N - 1] = mat[i][N - 1];
   }
   for (int i = 0; i < N; i++) {
      for (int j = 1; j < N; j++) {
         if (mat[i][j] == 1)
            conOneLeft[i][j] = conOneLeft[i][j - 1] + 1;
         else
            conOneLeft[i][j] = 0;
         if (mat[j][i] == 1)
            conOneTop[j][i] = conOneTop[j - 1][i] + 1;
         else
            conOneTop[j][i] = 0;
         j = N - 1 - j;
         if (mat[j][i] == 1)
            conOneBottom[j][i] = conOneBottom[j + 1][i] + 1;
         else
            conOneBottom[j][i] = 0;
         if (mat[i][j] == 1)
            conOneRight[i][j] = conOneRight[i][j + 1] + 1;
         else
            conOneRight[i][j] = 0;
         j = N - 1 - j;
      }
   }
   int maxConOne = 0;
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++){
         int ConOnes = min(min(conOneTop[i][j],
         conOneBottom[i][j]), min(conOneLeft[i][j], conOneRight[i][j]));
         if(ConOnes > maxConOne)
            maxConOne = ConOnes;
      }
   }
   if (maxConOne)
      return (4 * (maxConOne - 1) + 1);
   return 0;
}
int main() {
   int mat[N][N] = {
      { 1, 0, 1, 1, 1, 1, 0 },
      { 1, 0, 1, 0, 1, 1, 1 },
      { 1, 1, 1, 0, 1, 1, 0 },
      { 0, 0, 0, 0, 1, 0, 0 },
      { 1, 0, 1, 1, 1, 1, 1 },
      { 1, 1, 1, 0, 1, 1, 1 },
      { 1, 0, 0, 0, 1, 0, 0 },
   };
   cout<<"The size of the largest plus formed by ones is "<<findLargestPlusSize(mat);
   return 0;
}

Output

The size of the largest plus formed by ones is 9
raja
Published on 16-Mar-2021 06:24:32
Advertisements