Find length of the largest region in Boolean Matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2-D matrix of size nXm consisting of 0’s and 1’s only. Our task is to find the length of the largest region in the Boolean Matrix. 

Problem Description: If a cell contains 1, it is a filled Cell. We need to find the length of connected cells which are connected adjacent to each other horizontally or vertically or diagonally. 

Let’s take an example to understand the problem, 

Input: matrix[4][5]

{ {0, 1, 1, 0, 1},
   {0, 0, 1, 1, 1}, 

  {1, 0, 0, 0, 0},
   {1, 0, 1, 0, 1} }

Output: 6

Explanation:  

The number of connected filled cells is 1, 2, 6.

Solution Approach −

To solve the problem, we simply need to count the total number of connected cells of the matrix.

For this, we will perform DFS for the cell which will check for all neighbouring cells of the current cell (for a cell there can be 8 neighbours cells). For each cell, we need to check if it is visited by keeping track using a hash-map. And completion, we need to return the maximum count of visited cells.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
#define ROW 4
#define COL 5

int isNotVisited(int M[][COL], int row, int col, bool visited[][COL]) {
   
   return (row >= 0) && (row < ROW) && (col >= 0 ) && (col < COL) && (M[row][col] && !visited[row][col]);
}

void depthFirstSearch(int M[][COL], int row, int col, bool visited[][COL], int& count){
   
   static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
   static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
   visited[row][col] = true;

   for (int k = 0; k < 8; ++k) {
      if (isNotVisited(M, row + rowNbr[k], col + colNbr[k], visited)) {
         count++;
         depthFirstSearch(M, row + rowNbr[k], col + colNbr[k], visited, count);
      }
   }
}

int findLargestRegionLength(int M[][COL]) {
   
   bool isvisited[ROW][COL];
   memset(isvisited, 0, sizeof(isvisited));
   int maxCount = -1;
   for (int i = 0; i < ROW; ++i) {
      for (int j = 0; j < COL; ++j) {
         if (M[i][j] && !isvisited[i][j]) {

            int count = 1;
            depthFirstSearch(M, i, j, isvisited, count);
            maxCount = max(maxCount, count);
         }
      }
   }
   return maxCount;
}

int main(){
   int M[][COL] = { {0, 1, 1, 0, 1},
                {0, 0, 1, 1, 1},
                {1, 0, 0, 0, 0},
                {1, 0, 1, 0, 1} };

   cout<<"The length of largest region is "<<findLargestRegionLength(M);

   return 0;
}

Output

The length of largest region is 6
raja
Published on 25-Jan-2021 05:04:15
Advertisements