Output: 6 Explanation: The region in red has the largest area of 6 cells.
Area of Largest Region is 6
Input: M[][] = {{0, 0, 1, 1, 0}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 0, 1}} Output: 6 Explanation: In the following example, there are 2 regions. One with area = 1 and other with area = 6. So, largest area = 6.
Using DFS - O(rows * cols) Time and O(rows * cols) Space
The idea is to traverse the input matrix and if the value of any cell is 1, then run a DFS from the cell to visit all the cells in the connected component. In DFS, keep track of the area of the region and make recursive calls for all the eight neighbors. Also, while visiting any cell, update its value to 0 to mark it as visited. So, using the input matrix to mark the visited cells will avoid maintaining an extra 2D matrix to store the visited cells.
Below is the implementation of the above approach:
C++
// C++ Program to find area of the largest region of 1s#include<bits/stdc++.h>usingnamespacestd;// A function to check if cell(r, c) can be included in DFSboolisSafe(vector<vector<int>>&M,intr,intc,introws,intcols){// row number is in range, column number is in range and// value is 1 return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Depth-First-Search to visit all cells in the current islandvoidDFS(vector<vector<int>>&M,intr,intc,introws,intcols,int&area){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellvector<int>dirR={-1,-1,-1,0,0,1,1,1};vector<int>dirC={-1,0,1,-1,1,-1,0,1};// Increment area of region by 1area+=1;// Mark this cell as visitedM[r][c]=0;// Recur for all connected neighboursfor(inti=0;i<8;i++){intnewR=r+dirR[i];intnewC=c+dirC[i];if(isSafe(M,newR,newC,rows,cols))DFS(M,newR,newC,rows,cols,area);}}// function to find area of the largest region of 1sintlargestRegion(vector<vector<int>>&M){introws=M.size(),cols=M[0].size();// Initialize result as 0 and traverse through the// all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=0;DFS(M,i,j,rows,cols,area);// maximize the area maxArea=max(maxArea,area);}}}returnmaxArea;}intmain(){vector<vector<int>>M={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};cout<<largestRegion(M);return0;}
C
// C Program to find area of the largest region of 1s#include<stdio.h>#include<stdlib.h>// Define constants for rows and columns#define ROWS 5#define COLS 7// A function to check if cell(r, c) can be included in DFSintisSafe(intM[ROWS][COLS],intr,intc,introws,intcols){// Row number is in range, column number is in range,// and value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Depth-First-Search to visit all cells in the current islandvoidDFS(intM[ROWS][COLS],intr,intc,introws,intcols,int*area){// These arrays are used to get row and column numbers of 8 // neighbours of a given cellintdirR[]={-1,-1,-1,0,0,1,1,1};intdirC[]={-1,0,1,-1,1,-1,0,1};// Increment area of region by 1(*area)++;// Mark this cell as visitedM[r][c]=0;// Recur for all connected neighboursfor(inti=0;i<8;i++){intnewR=r+dirR[i];intnewC=c+dirC[i];if(isSafe(M,newR,newC,rows,cols)){DFS(M,newR,newC,rows,cols,area);}}}// Function to find area of the largest region of 1sintlargestRegion(intM[ROWS][COLS],introws,intcols){// Initialize result as 0 and traverse through // all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=0;DFS(M,i,j,rows,cols,&area);// Maximize the areaif(area>maxArea){maxArea=area;}}}}returnmaxArea;}intmain(){intM[ROWS][COLS]={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};printf("%d\n",largestRegion(M,ROWS,COLS));return0;}
Java
// Java Program to find area of the largest region of 1simportjava.util.*;classGfG{// A function to check if cell(r, c) can be included in DFSstaticbooleanisSafe(int[][]M,intr,intc,introws,intcols){// row number is in range, column number is in range and// value is 1 return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Depth-First-Search to visit all cells in the current islandstaticvoidDFS(int[][]M,intr,intc,introws,intcols,int[]area){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellint[]dirR={-1,-1,-1,0,0,1,1,1};int[]dirC={-1,0,1,-1,1,-1,0,1};// Increment area of region by 1area[0]+=1;// Mark this cell as visitedM[r][c]=0;// Recur for all connected neighboursfor(inti=0;i<8;i++){intnewR=r+dirR[i];intnewC=c+dirC[i];if(isSafe(M,newR,newC,rows,cols)){DFS(M,newR,newC,rows,cols,area);}}}// function to find area of the largest region of 1sstaticintlargestRegion(int[][]M){introws=M.length;intcols=M[0].length;// Initialize result as 0 and traverse through the// all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){// area is taken as an array of size 1 to // achieve pass by reference int[]area={0};DFS(M,i,j,rows,cols,area);// maximize the area maxArea=Math.max(maxArea,area[0]);}}}returnmaxArea;}publicstaticvoidmain(String[]args){int[][]M={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};System.out.println(largestRegion(M));}}
Python
# Python Program to find area of the largest region of 1s# A function to check if cell(r, c) can be included in DFSdefis_safe(M,r,c,rows,cols):# row number is in range, column number is in range and# value is 1 return(r>=0andr<rows)and(c>=0andc<cols) \
and(M[r][c]==1)# Depth-First-Search to visit all cells in the current islanddefdfs(M,r,c,rows,cols,area):# Depth-First-Search to visit all cells in the current island# These arrays are used to get row and column# numbers of 8 neighbours of a given celldirR=[-1,-1,-1,0,0,1,1,1]dirC=[-1,0,1,-1,1,-1,0,1]# Increment area of region by 1area[0]+=1# Mark this cell as visitedM[r][c]=0# Recur for all connected neighboursforiinrange(8):new_r=r+dirR[i]new_c=c+dirC[i]ifis_safe(M,new_r,new_c,rows,cols):dfs(M,new_r,new_c,rows,cols,area)# function to find area of the largest region of 1sdeflargest_region(M):# function to find area of the largest region of 1srows=len(M)cols=len(M[0])# Initialize result as 0 and traverse through the# all cells of given matrixmax_area=0foriinrange(rows):forjinrange(cols):# If a cell with value 1 is foundifM[i][j]==1:# area is taken as a list of size 1 to # achieve pass by referencearea=[0]dfs(M,i,j,rows,cols,area)# maximize the area max_area=max(max_area,area[0])returnmax_areaif__name__=="__main__":M=[[1,0,0,0,1,0,0],[0,1,0,0,1,1,1],[1,1,0,0,0,0,0],[1,0,0,1,1,0,0],[1,0,0,1,0,1,1]]print(largest_region(M))
C#
// C# Program to find area of the largest region of 1susingSystem;usingSystem.Collections.Generic;classGfG{// A function to check if cell(r, c) can be included in DFSstaticboolIsSafe(int[][]M,intr,intc,introws,intcols){// row number is in range, column number is in range // and value is 1 return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Depth-First-Search to visit all cells in the current islandstaticvoidDFS(int[][]M,intr,intc,introws,intcols,refintarea){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellint[]dirR={-1,-1,-1,0,0,1,1,1};int[]dirC={-1,0,1,-1,1,-1,0,1};// Increment area of region by 1area+=1;// Mark this cell as visitedM[r][c]=0;// Recur for all connected neighboursfor(inti=0;i<8;i++){intnewR=r+dirR[i];intnewC=c+dirC[i];if(IsSafe(M,newR,newC,rows,cols))DFS(M,newR,newC,rows,cols,refarea);}}// function to find area of the largest region of 1sstaticintLargestRegion(int[][]M){introws=M.GetLength(0);intcols=M[0].GetLength(0);// Initialize result as 0 and traverse through the// all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=0;DFS(M,i,j,rows,cols,refarea);// maximize the area maxArea=Math.Max(maxArea,area);}}}returnmaxArea;}staticvoidMain(){int[][]M={newint[]{1,0,0,0,1,0,0},newint[]{0,1,0,0,1,1,1},newint[]{1,1,0,0,0,0,0},newint[]{1,0,0,1,1,0,0},newint[]{1,0,0,1,0,1,1}};Console.WriteLine(LargestRegion(M));}}
JavaScript
// JavaScript Program to find area of the largest region of 1s// A function to check if cell(r, c) can be included in DFSfunctionisSafe(M,r,c,rows,cols){// row number is in range, column number is in range and// value is 1 return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]===1);}// Depth-First-Search to visit all cells in the current islandfunctionDFS(M,r,c,rows,cols,area){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellconstdirR=[-1,-1,-1,0,0,1,1,1];constdirC=[-1,0,1,-1,1,-1,0,1];// Increment area of region by 1area[0]+=1;// Mark this cell as visitedM[r][c]=0;// Recur for all connected neighboursfor(leti=0;i<8;i++){constnewR=r+dirR[i];constnewC=c+dirC[i];if(isSafe(M,newR,newC,rows,cols)){DFS(M,newR,newC,rows,cols,area);}}}// Function to find area of the largest region of 1sfunctionlargestRegion(M){constrows=M.length;constcols=M[0].length;// Initialize result as 0 and traverse through the// all cells of given matrixletmaxArea=0;for(leti=0;i<rows;i++){for(letj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]===1){// area is taken as list to achieve // pass by referenceletarea=[0];DFS(M,i,j,rows,cols,area);// Maximize the area maxArea=Math.max(maxArea,area[0]);}}}returnmaxArea;}// Example usageconstM=[[1,0,0,0,1,0,0],[0,1,0,0,1,1,1],[1,1,0,0,0,0,0],[1,0,0,1,1,0,0],[1,0,0,1,0,1,1]];console.log(largestRegion(M));
Output
6
Time complexity: O(rows * cols). In the worst case, all the cells will be visited so the time complexity is O(rows * cols). Auxiliary Space: O(rows * cols) for recursive stack space.
Using BFS - O(rows * cols) Time and O(rows + cols) Space
The idea is to traverse the input matrix and if the value of any cell is 1, then run a BFS from the cell to visit all the cells in the connected component. In BFS, maintain a queue to store the nodes and its neighbors. Also, while visiting any cell, update its value to 0 to mark it as visited. So, using the input matrix to mark the visited cells will avoid maintaining an extra 2D matrix to store the visited cells.
Below is the implementation of the above approach:
C++
// C++ Program to find area of the largest region of 1s#include<bits/stdc++.h>usingnamespacestd;// A function to check if cell(r, c) can be included in DFSboolisSafe(vector<vector<int>>&M,intr,intc,introws,intcols){// row number is in range, column number is in range and// value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Breadth-First-Search to visit all cells in the current islandintBFS(vector<vector<int>>&M,intr,intc,introws,intcols){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellvector<int>dirR={-1,-1,-1,0,0,1,1,1};vector<int>dirC={-1,0,1,-1,1,-1,0,1};intarea=0;// create a queue for bfs traversalqueue<pair<int,int>>q;// Push the cell(r, c) into queue and mark it as visitedq.push({r,c});M[r][c]=0;while(!q.empty()){pair<int,int>curr=q.front();q.pop();// Increment the area of regionarea+=1;// Recur for all 8 connected neighboursfor(inti=0;i<8;i++){intnewR=curr.first+dirR[i];intnewC=curr.second+dirC[i];if(isSafe(M,newR,newC,rows,cols)){M[newR][newC]=0;q.push({newR,newC});}}}returnarea;}// function to find area of the largest region of 1sintlargestRegion(vector<vector<int>>&M){introws=M.size(),cols=M[0].size();// Initialize result as 0 and traverse through the// all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=BFS(M,i,j,rows,cols);// maximize the area maxArea=max(maxArea,area);}}}returnmaxArea;}intmain(){vector<vector<int>>M={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};cout<<largestRegion(M);return0;}
C
// C Program to find area of the largest region of 1s#include<stdio.h>// Define the maximum size of the matrix and queue#define MAX_ROWS 100#define MAX_COLS 100#define MAX_QUEUE_SIZE MAX_ROWS * MAX_COLS// Define a structure for the queue to store pairs of integersstructPair{introw,col;};intisSafe(intM[MAX_ROWS][MAX_COLS],intr,intc,introws,intcols){// Row number is in range, column number is in range, and value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Breadth-First-Search to visit all cells in the current islandintBFS(intM[MAX_ROWS][MAX_COLS],intr,intc,introws,intcols){// These arrays are used to get row and column numbers of // 8 neighbours of a given cellintdirR[]={-1,-1,-1,0,0,1,1,1};intdirC[]={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversalstructPairqueue[MAX_QUEUE_SIZE];intfront=0,rear=0;// Push the cell(r, c) into queue and mark it as visitedqueue[rear++]=(structPair){r,c};M[r][c]=0;while(front<rear){structPaircurr=queue[front++];// Increment the area of regionarea+=1;// Recur for all 8 connected neighboursfor(inti=0;i<8;i++){intnewR=curr.row+dirR[i];intnewC=curr.col+dirC[i];if(isSafe(M,newR,newC,rows,cols)){M[newR][newC]=0;queue[rear++]=(structPair){newR,newC};}}}returnarea;}// Function to find the area of the largest region of 1sintlargestRegion(intM[MAX_ROWS][MAX_COLS],introws,intcols){// Initialize result as 0 and traverse through all cells // of the given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=BFS(M,i,j,rows,cols);// Maximize the areaif(area>maxArea){maxArea=area;}}}}returnmaxArea;}intmain(){// Define the matrix directlyintM[MAX_ROWS][MAX_COLS]={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};introws=5,cols=7;// Matrix dimensionsprintf("%d\n",largestRegion(M,rows,cols));return0;}
Java
// Java Program to find area of the largest region of 1simportjava.util.LinkedList;importjava.util.Queue;publicclassGfG{// A function to check if cell(r, c) can be included in BFSstaticbooleanisSafe(int[][]M,intr,intc,introws,intcols){// row number is in range, column number is in range and// value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Breadth-First-Search to visit all cells in the current islandstaticintBFS(int[][]M,intr,intc,introws,intcols){// These arrays are used to get row and column// numbers of 8 neighbours of a given cellint[]dirR={-1,-1,-1,0,0,1,1,1};int[]dirC={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversalQueue<int[]>q=newLinkedList<>();// Push the cell(r, c) into queue and mark it as visitedq.add(newint[]{r,c});M[r][c]=0;while(!q.isEmpty()){int[]curr=q.poll();intcurrR=curr[0];intcurrC=curr[1];// Increment the area of regionarea+=1;// Recur for all 8 connected neighboursfor(inti=0;i<8;i++){intnewR=currR+dirR[i];intnewC=currC+dirC[i];if(isSafe(M,newR,newC,rows,cols)){M[newR][newC]=0;q.add(newint[]{newR,newC});}}}returnarea;}// Function to find area of the largest region of 1sstaticintlargestRegion(int[][]M){introws=M.length;intcols=M[0].length;// Initialize result as 0 and traverse through the// all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=BFS(M,i,j,rows,cols);// Maximize the area maxArea=Math.max(maxArea,area);}}}returnmaxArea;}publicstaticvoidmain(String[]args){int[][]M={{1,0,0,0,1,0,0},{0,1,0,0,1,1,1},{1,1,0,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,1,0,1,1}};System.out.println(largestRegion(M));}}
Python
# Python Program to find area of the largest region of 1sfromcollectionsimportdeque# A function to check if cell(r, c) can be included in BFSdefisSafe(M,r,c,rows,cols):# row number is in range, column number is in range and# value is 1return(r>=0andr<rows)and(c>=0andc<cols)and(M[r][c]==1)# Breadth-First-Search to visit all cells in the current islanddefBFS(M,r,c,rows,cols):# These arrays are used to get row and column# numbers of 8 neighbours of a given celldirR=[-1,-1,-1,0,0,1,1,1]dirC=[-1,0,1,-1,1,-1,0,1]area=0# create a queue for bfs traversalq=deque()# Push the cell(r, c) into queue and mark it as visitedq.append((r,c))M[r][c]=0whileq:curr=q.popleft()# Increment the area of regionarea+=1# Recur for all 8 connected neighboursforiinrange(8):newR=curr[0]+dirR[i]newC=curr[1]+dirC[i]ifisSafe(M,newR,newC,rows,cols):M[newR][newC]=0q.append((newR,newC))returnarea# Function to find area of the largest region of 1sdeflargestRegion(M):rows=len(M)cols=len(M[0])# Initialize result as 0 and traverse through the# all cells of given matrixmaxArea=0foriinrange(rows):forjinrange(cols):# If a cell with value 1 is foundifM[i][j]==1:area=BFS(M,i,j,rows,cols)# Maximize the area maxArea=max(maxArea,area)returnmaxAreaif__name__=="__main__":M=[[1,0,0,0,1,0,0],[0,1,0,0,1,1,1],[1,1,0,0,0,0,0],[1,0,0,1,1,0,0],[1,0,0,1,0,1,1]]print(largestRegion(M))
C#
// C# Program to find area of the largest region of 1susingSystem;usingSystem.Collections.Generic;classGfG{// A function to check if cell(r, c) can be included in BFSstaticboolIsSafe(int[][]M,intr,intc,introws,intcols){// row number is in range, column number is in range and value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]==1);}// Breadth-First-Search to visit all cells in the current islandstaticintBFS(int[][]M,intr,intc,introws,intcols){// These arrays are used to get row and column numbers of 8 neighbors of a given cellint[]dirR={-1,-1,-1,0,0,1,1,1};int[]dirC={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversalQueue<Tuple<int,int>>q=newQueue<Tuple<int,int>>();// Push the cell(r, c) into queue and mark it as visitedq.Enqueue(Tuple.Create(r,c));M[r][c]=0;while(q.Count>0){varcurr=q.Dequeue();intcurrR=curr.Item1;intcurrC=curr.Item2;// Increment the area of regionarea+=1;// Recur for all 8 connected neighborsfor(inti=0;i<8;i++){intnewR=currR+dirR[i];intnewC=currC+dirC[i];if(IsSafe(M,newR,newC,rows,cols)){M[newR][newC]=0;q.Enqueue(Tuple.Create(newR,newC));}}}returnarea;}// Function to find area of the largest region of 1sstaticintLargestRegion(int[][]M){introws=M.Length;intcols=M[0].Length;// Initialize result as 0 and traverse through all cells of given matrixintmaxArea=0;for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]==1){intarea=BFS(M,i,j,rows,cols);// Maximize the area maxArea=Math.Max(maxArea,area);}}}returnmaxArea;}staticvoidMain(){int[][]M={newint[]{1,0,0,0,1,0,0},newint[]{0,1,0,0,1,1,1},newint[]{1,1,0,0,0,0,0},newint[]{1,0,0,1,1,0,0},newint[]{1,0,0,1,0,1,1}};Console.WriteLine(LargestRegion(M));}}
JavaScript
// JavaScript Program to find area of the largest region of 1s// Function to check if cell(r, c) can be included in BFSfunctionisSafe(M,r,c,rows,cols){// Row number is in range, column number is in range and value is 1return(r>=0&&r<rows)&&(c>=0&&c<cols)&&(M[r][c]===1);}// Breadth-First-Search to visit all cells in the current islandfunctionBFS(M,r,c,rows,cols){// These arrays are used to get row and column numbers // of 8 neighbors of a given cellconstdirR=[-1,-1,-1,0,0,1,1,1];constdirC=[-1,0,1,-1,1,-1,0,1];letarea=0;// Create a queue for BFS traversalconstqueue=[];// Push the cell(r, c) into queue and mark it as visitedqueue.push([r,c]);M[r][c]=0;while(queue.length>0){const[currR,currC]=queue.shift();// Increment the area of regionarea+=1;// Recur for all 8 connected neighborsfor(leti=0;i<8;i++){constnewR=currR+dirR[i];constnewC=currC+dirC[i];if(isSafe(M,newR,newC,rows,cols)){M[newR][newC]=0;queue.push([newR,newC]);}}}returnarea;}// Function to find area of the largest region of 1sfunctionlargestRegion(M){constrows=M.length;constcols=M[0].length;letmaxArea=0;for(leti=0;i<rows;i++){for(letj=0;j<cols;j++){// If a cell with value 1 is foundif(M[i][j]===1){constarea=BFS(M,i,j,rows,cols);// Maximize the areamaxArea=Math.max(maxArea,area);}}}returnmaxArea;}constM=[[1,0,0,0,1,0,0],[0,1,0,0,1,1,1],[1,1,0,0,0,0,0],[1,0,0,1,1,0,0],[1,0,0,1,0,1,1]];console.log(largestRegion(M));
Output
6
Time complexity: O(rows * cols). In the worst case, all the cells will be visited so the time complexity is O(rows * cols). Auxiliary Space: O(rows + cols), in the worst case when all the cells are 1, then the size of queue can grow up to (rows + cols).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.