Given a grid of dimensions n x m containing 0's and 1's. Find the count of 1's in the largest region of 1's. A region of 1's is a group of 1's where two 1s can be adjacent to each other in any of the 8 directions (2 horizontal, 2 vertical and 4 diagonals).
Examples:
Input: grid[][]= [[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 1]] Output: 6 Explanation: The region in red has the largest area of 6 cells.
Input: grid[][] = [[1, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0]] Output: 5 Explanation: The largest region has five 1s.
The idea is to use DFS to explore each connected region of 1s in the grid. Since diagonal cells are also considered connected, we check all 8 neighbouring directions. Whenever we find an unvisited 1, we run DFS, count its cells, and keep track of the maximum region area.
Traverse every cell of the grid.
If the current cell contains 1, start a DFS from that cell.
Mark the visited cell as 0 and increment the current region's area.
Recursively visit all valid 1 cells among the 8 neighbouring directions.
After DFS completes, update maxArea with the current region's area.
Return maxArea after processing the entire grid.
C++
#include<bits/stdc++.h>usingnamespacestd;// Checks whether the cell is valid and contains 1.boolisSafe(vector<vector<int>>&grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// DFS to find the area of the current region.voidDFS(vector<vector<int>>&grid,intr,intc,introws,intcols,int&area){// Directions for all 8 neighbouring cells.intdr[]={-1,-1,-1,0,0,1,1,1};intdc[]={-1,0,1,-1,1,-1,0,1};// Mark the current cell as visited.grid[r][c]=0;// Increase the area of the current region.area++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=r+dr[i];intnc=c+dc[i];if(isSafe(grid,nr,nc,rows,cols))DFS(grid,nr,nc,rows,cols,area);}}// Returns the area of the largest region of 1s.intlargestRegion(vector<vector<int>>&grid){introws=grid.size();intcols=grid[0].size();intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start DFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=0;DFS(grid,r,c,rows,cols,area);// Update the maximum region area.maxArea=max(maxArea,area);}}}returnmaxArea;}intmain(){vector<vector<int>>grid={{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(grid)<<endl;return0;}
C
#include<stdio.h>// Checks whether the cell is valid and contains 1.intisSafe(intgrid[][7],intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// DFS to find the area of the current region.voidDFS(intgrid[][7],intr,intc,introws,intcols,int*area){// Directions for all 8 neighbouring cells.intdr[]={-1,-1,-1,0,0,1,1,1};intdc[]={-1,0,1,-1,1,-1,0,1};// Mark the current cell as visited.grid[r][c]=0;// Increase the area of the current region.(*area)++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=r+dr[i];intnc=c+dc[i];if(isSafe(grid,nr,nc,rows,cols))DFS(grid,nr,nc,rows,cols,area);}}// Returns the area of the largest region of 1s.intlargestRegion(intgrid[][7],introws,intcols){intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start DFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=0;DFS(grid,r,c,rows,cols,&area);// Update the maximum region area.if(area>maxArea)maxArea=area;}}}returnmaxArea;}intmain(){intgrid[5][7]={{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(grid,5,7));return0;}
Java
classGFG{// Checks whether the cell is valid and contains 1.staticbooleanisSafe(int[][]grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// DFS to find the area of the current region.staticintDFS(int[][]grid,intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Mark the current cell as visited.grid[r][c]=0;// Increase the area of the current region.intarea=1;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=r+dr[i];intnc=c+dc[i];if(isSafe(grid,nr,nc,rows,cols))area+=DFS(grid,nr,nc,rows,cols);}returnarea;}// Returns the area of the largest region of 1s.staticintlargestRegion(int[][]grid){introws=grid.length;intcols=grid[0].length;intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start DFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=DFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.max(maxArea,area);}}}returnmaxArea;}publicstaticvoidmain(String[]args){int[][]grid={{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(grid));}}
Python
# Checks whether the cell is valid and contains 1.defisSafe(grid,r,c,rows,cols):return(r>=0andr<rowsandc>=0andc<colsandgrid[r][c]==1)# DFS to find the area of the current region.defDFS(grid,r,c,rows,cols):# Directions for all 8 neighbouring cells.dr=[-1,-1,-1,0,0,1,1,1]dc=[-1,0,1,-1,1,-1,0,1]# Mark the current cell as visited.grid[r][c]=0# Increase the area of the current region.area=1# Visit all 8 neighbouring cells.foriinrange(8):nr=r+dr[i]nc=c+dc[i]ifisSafe(grid,nr,nc,rows,cols):area+=DFS(grid,nr,nc,rows,cols)returnarea# Returns the area of the largest region of 1s.deflargestRegion(grid):rows=len(grid)cols=len(grid[0])maxArea=0# Traverse every cell of the grid.forrinrange(rows):forcinrange(cols):# Start DFS if an unvisited 1 is found.ifgrid[r][c]==1:area=DFS(grid,r,c,rows,cols)# Update the maximum region area.maxArea=max(maxArea,area)returnmaxArea# Driver Codeif__name__=="__main__":grid=[[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(grid))
C#
usingSystem;classGFG{// Checks whether the cell is valid and contains 1.staticboolisSafe(int[,]grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r,c]==1;}// DFS to find the area of the current region.staticintDFS(int[,]grid,intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};// Mark the current cell as visited.grid[r,c]=0;// Increase the area of the current region.intarea=1;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=r+dr[i];intnc=c+dc[i];if(isSafe(grid,nr,nc,rows,cols))area+=DFS(grid,nr,nc,rows,cols);}returnarea;}// Returns the area of the largest region of 1s.staticintlargestRegion(int[,]grid){introws=grid.GetLength(0);intcols=grid.GetLength(1);intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start DFS if an unvisited 1 is found.if(grid[r,c]==1){intarea=DFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.Max(maxArea,area);}}}returnmaxArea;}publicstaticvoidMain(){int[,]grid={{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.WriteLine(largestRegion(grid));}}
JavaScript
// Checks whether the cell is valid and contains 1.functionisSafe(grid,r,c,rows,cols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]===1;}// DFS to find the area of the current region.functionDFS(grid,r,c,rows,cols){// Directions for all 8 neighbouring cells.constdr=[-1,-1,-1,0,0,1,1,1];constdc=[-1,0,1,-1,1,-1,0,1];// Mark the current cell as visited.grid[r][c]=0;// Increase the area of the current region.letarea=1;// Visit all 8 neighbouring cells.for(leti=0;i<8;i++){constnr=r+dr[i];constnc=c+dc[i];if(isSafe(grid,nr,nc,rows,cols))area+=DFS(grid,nr,nc,rows,cols);}returnarea;}// Returns the area of the largest region of 1s.functionlargestRegion(grid){constrows=grid.length;constcols=grid[0].length;letmaxArea=0;// Traverse every cell of the grid.for(letr=0;r<rows;r++){for(letc=0;c<cols;c++){// Start DFS if an unvisited 1 is found.if(grid[r][c]===1){constarea=DFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.max(maxArea,area);}}}returnmaxArea;}// Driver Codeconstgrid=[[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(grid));
Output
6
Using BFS - O(n * m) Time and O(n * m) Space
The idea is to use BFS to explore each connected region of 1s in the grid. Since diagonal cells are also connected, we check all 8 neighbouring directions. Whenever an unvisited 1 is found, BFS visits the complete region and counts its cells. Finally, keep track of the maximum area among all regions.
Traverse every cell of the grid.
If the cell contains an unvisited 1, start BFS from that cell.
Mark each visited 1 as 0 and add it to the queue.
For every cell, check all 8 neighbouring directions and visit valid 1s.
Count the number of cells visited in the current region.
Update maxArea and return it after traversing the entire grid.
C++
#include<bits/stdc++.h>usingnamespacestd;// Checks whether the cell is valid and contains 1.boolisSafe(vector<vector<int>>&grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// Breadth-First Search to find the area of the current region.intBFS(vector<vector<int>>&grid,intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.intdr[]={-1,-1,-1,0,0,1,1,1};intdc[]={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversal.queue<pair<int,int>>q;// Push the starting cell and mark it as visited.q.push({r,c});grid[r][c]=0;while(!q.empty()){autocurr=q.front();q.pop();// Increment the area of the region.area++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=curr.first+dr[i];intnc=curr.second+dc[i];if(isSafe(grid,nr,nc,rows,cols)){// Mark the cell as visited.grid[nr][nc]=0;// Add the cell to the queue.q.push({nr,nc});}}}returnarea;}// Returns the area of the largest region of 1s.intlargestRegion(vector<vector<int>>&grid){introws=grid.size();intcols=grid[0].size();intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start BFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=BFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=max(maxArea,area);}}}returnmaxArea;}intmain(){vector<vector<int>>grid={{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(grid)<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>// Checks whether the cell is valid and contains 1.intisSafe(intgrid[][7],intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// Breadth-First Search to find the area of the current region.intBFS(intgrid[][7],intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.intdr[]={-1,-1,-1,0,0,1,1,1};intdc[]={-1,0,1,-1,1,-1,0,1};intarea=0;// Create arrays for the BFS queue.intqueue[100][2];intfront=0,rear=0;// Push the starting cell and mark it as visited.queue[rear][0]=r;queue[rear][1]=c;rear++;grid[r][c]=0;while(front<rear){intcurrR=queue[front][0];intcurrC=queue[front][1];front++;// Increment the area of the region.area++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=currR+dr[i];intnc=currC+dc[i];if(isSafe(grid,nr,nc,rows,cols)){// Mark the cell as visited.grid[nr][nc]=0;// Add the cell to the queue.queue[rear][0]=nr;queue[rear][1]=nc;rear++;}}}returnarea;}// Returns the area of the largest region of 1s.intlargestRegion(intgrid[][7],introws,intcols){intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start BFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=BFS(grid,r,c,rows,cols);// Update the maximum region area.if(area>maxArea)maxArea=area;}}}returnmaxArea;}intmain(){intgrid[5][7]={{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(grid,5,7));return0;}
Java
importjava.util.*;classGFG{// Checks whether the cell is valid and contains 1.staticbooleanisSafe(int[][]grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]==1;}// Breadth-First Search to find the area of the current// region.staticintBFS(int[][]grid,intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversal.Queue<int[]>q=newLinkedList<>();// Push the starting cell and mark it as visited.q.offer(newint[]{r,c});grid[r][c]=0;while(!q.isEmpty()){int[]curr=q.poll();// Increment the area of the region.area++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=curr[0]+dr[i];intnc=curr[1]+dc[i];if(isSafe(grid,nr,nc,rows,cols)){// Mark the cell as visited.grid[nr][nc]=0;// Add the cell to the queue.q.offer(newint[]{nr,nc});}}}returnarea;}// Returns the area of the largest region of 1s.staticintlargestRegion(int[][]grid){introws=grid.length;intcols=grid[0].length;intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start BFS if an unvisited 1 is found.if(grid[r][c]==1){intarea=BFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.max(maxArea,area);}}}returnmaxArea;}publicstaticvoidmain(String[]args){int[][]grid={{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(grid));}}
Python
fromcollectionsimportdeque# Checks whether the cell is valid and contains 1.defisSafe(grid,r,c,rows,cols):returnr>=0andr<rowsandc>=0andc<colsandgrid[r][c]==1# Breadth-First Search to find the area of the current region.defBFS(grid,r,c,rows,cols):# Directions for all 8 neighbouring cells.dr=[-1,-1,-1,0,0,1,1,1]dc=[-1,0,1,-1,1,-1,0,1]area=0# Create a queue for BFS traversal.q=deque()# Push the starting cell and mark it as visited.q.append((r,c))grid[r][c]=0whileq:curr=q.popleft()# Increment the area of the region.area+=1# Visit all 8 neighbouring cells.foriinrange(8):nr=curr[0]+dr[i]nc=curr[1]+dc[i]ifisSafe(grid,nr,nc,rows,cols):# Mark the cell as visited.grid[nr][nc]=0# Add the cell to the queue.q.append((nr,nc))returnarea# Returns the area of the largest region of 1s.deflargestRegion(grid):rows=len(grid)cols=len(grid[0])maxArea=0# Traverse every cell of the grid.forrinrange(rows):forcinrange(cols):# Start BFS if an unvisited 1 is found.ifgrid[r][c]==1:area=BFS(grid,r,c,rows,cols)# Update the maximum region area.maxArea=max(maxArea,area)returnmaxArea# Driver Codeif__name__=="__main__":grid=[[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(grid))
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Checks whether the cell is valid and contains 1.staticboolisSafe(int[,]grid,intr,intc,introws,intcols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r,c]==1;}// Breadth-First Search to find the area of the current// region.staticintBFS(int[,]grid,intr,intc,introws,intcols){// Directions for all 8 neighbouring cells.int[]dr={-1,-1,-1,0,0,1,1,1};int[]dc={-1,0,1,-1,1,-1,0,1};intarea=0;// Create a queue for BFS traversal.Queue<(int,int)>q=newQueue<(int,int)>();// Push the starting cell and mark it as visited.q.Enqueue((r,c));grid[r,c]=0;while(q.Count>0){varcurr=q.Dequeue();// Increment the area of the region.area++;// Visit all 8 neighbouring cells.for(inti=0;i<8;i++){intnr=curr.Item1+dr[i];intnc=curr.Item2+dc[i];if(isSafe(grid,nr,nc,rows,cols)){// Mark the cell as visited.grid[nr,nc]=0;// Add the cell to the queue.q.Enqueue((nr,nc));}}}returnarea;}// Returns the area of the largest region of 1s.staticintlargestRegion(int[,]grid){introws=grid.GetLength(0);intcols=grid.GetLength(1);intmaxArea=0;// Traverse every cell of the grid.for(intr=0;r<rows;r++){for(intc=0;c<cols;c++){// Start BFS if an unvisited 1 is found.if(grid[r,c]==1){intarea=BFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.Max(maxArea,area);}}}returnmaxArea;}staticvoidMain(){int[,]grid={{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.WriteLine(largestRegion(grid));}}
JavaScript
// Checks whether the cell is valid and contains 1.functionisSafe(grid,r,c,rows,cols){returnr>=0&&r<rows&&c>=0&&c<cols&&grid[r][c]===1;}// Breadth-First Search to find the area of the current// region.functionBFS(grid,r,c,rows,cols){// Directions for all 8 neighbouring cells.constdr=[-1,-1,-1,0,0,1,1,1];constdc=[-1,0,1,-1,1,-1,0,1];letarea=0;// Create a queue for BFS traversal.constq=[];// Push the starting cell and mark it as visited.q.push([r,c]);grid[r][c]=0;letfront=0;while(front<q.length){constcurr=q[front++];// Increment the area of the region.area++;// Visit all 8 neighbouring cells.for(leti=0;i<8;i++){constnr=curr[0]+dr[i];constnc=curr[1]+dc[i];if(isSafe(grid,nr,nc,rows,cols)){// Mark the cell as visited.grid[nr][nc]=0;// Add the cell to the queue.q.push([nr,nc]);}}}returnarea;}// Returns the area of the largest region of 1s.functionlargestRegion(grid){constrows=grid.length;constcols=grid[0].length;letmaxArea=0;// Traverse every cell of the grid.for(letr=0;r<rows;r++){for(letc=0;c<cols;c++){// Start BFS if an unvisited 1 is found.if(grid[r][c]===1){constarea=BFS(grid,r,c,rows,cols);// Update the maximum region area.maxArea=Math.max(maxArea,area);}}}returnmaxArea;}// Driver Codeconstgrid=[[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(grid));