Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Max Area of Island - Largest in Boolean Matrix
Next article icon

Max Area of Island - Largest in Boolean Matrix

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a binary 2D matrix, find area of the largest region of 1s which are connected horizontally, vertically or diagonally.

Examples:

Input: M[][]= {{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.

Max-Area-of-Island
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.

Table of Content

  • Using DFS - O(rows * cols) Time and O(rows * cols) Space
  • Using BFS - O(rows * cols) Time and O(rows + cols) Space

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> using namespace std;  // A function to check if cell(r, c) can be included in DFS bool isSafe(vector<vector<int>> &M, int r, int c, int rows, int 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 island void DFS(vector<vector<int>> &M, int r, int c,           						int rows, int cols, int &area) {        	// These arrays are used to get row and column 	// numbers of 8 neighbours of a given cell     vector<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 1   	area += 1;   	     // Mark this cell as visited     M[r][c] = 0;      // Recur for all connected neighbours     for (int i = 0; i < 8; i++) {       	int newR = r + dirR[i];       	int newC = 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 1s int largestRegion(vector<vector<int>> &M) {    	int rows = M.size(), cols = M[0].size();        // Initialize result as 0 and traverse through the     // all cells of given matrix     int maxArea = 0;     for (int i = 0; i < rows; i++) {         for (int j = 0; j < cols; j++) {           	             // If a cell with value 1 is found             if (M[i][j] == 1) {                 int area = 0;                 DFS(M, i, j, rows, cols, area);                  // maximize the area                  maxArea = max(maxArea, area);             }         }     }     return maxArea; }  int main() {     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);      return 0; } 
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 DFS int isSafe(int M[ROWS][COLS], int r, int c, int rows, int 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 island void DFS(int M[ROWS][COLS], int r, int c, int rows, int cols, int *area) {   	     // These arrays are used to get row and column numbers of 8    	// neighbours of a given cell     int dirR[] = {-1, -1, -1, 0, 0, 1, 1, 1};     int dirC[] = {-1, 0, 1, -1, 1, -1, 0, 1};      // Increment area of region by 1     (*area)++;      // Mark this cell as visited     M[r][c] = 0;      // Recur for all connected neighbours     for (int i = 0; i < 8; i++) {         int newR = r + dirR[i];         int newC = 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 1s int largestRegion(int M[ROWS][COLS], int rows, int cols) {   	     // Initialize result as 0 and traverse through    	// all cells of given matrix     int maxArea = 0;     for (int i = 0; i < rows; i++) {         for (int j = 0; j < cols; j++) {             // If a cell with value 1 is found             if (M[i][j] == 1) {                 int area = 0;                 DFS(M, i, j, rows, cols, &area);                  // Maximize the area                 if (area > maxArea) {                     maxArea = area;                 }             }         }     }     return maxArea; }  int main() {     int M[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));      return 0; } 
Java
// Java Program to find area of the largest region of 1s  import java.util.*;  class GfG {   	     // A function to check if cell(r, c) can be included in DFS     static boolean isSafe(int[][] M, int r, int c, int rows, int 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 island     static void DFS(int[][] M, int r, int c, int rows, int cols, int[] area) {       	         // These arrays are used to get row and column         // numbers of 8 neighbours of a given cell         int[] dirR = {-1, -1, -1, 0, 0, 1, 1, 1};         int[] dirC = {-1, 0, 1, -1, 1, -1, 0, 1};          // Increment area of region by 1         area[0] += 1;          // Mark this cell as visited         M[r][c] = 0;          // Recur for all connected neighbours         for (int i = 0; i < 8; i++) {             int newR = r + dirR[i];             int newC = 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 1s     static int largestRegion(int[][] M) {         int rows = M.length;         int cols = M[0].length;          // Initialize result as 0 and traverse through the         // all cells of given matrix         int maxArea = 0;         for (int i = 0; i < rows; i++) {             for (int j = 0; j < cols; j++) {                 // If a cell with value 1 is found                 if (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]);                 }             }         }         return maxArea;     }      public static void main(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 DFS def is_safe(M, r, c, rows, cols):   	     # row number is in range, column number is in range and     # value is 1      return (r >= 0 and r < rows) and (c >= 0 and c < cols) \   										and (M[r][c] == 1)  # Depth-First-Search to visit all cells in the current island def dfs(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 cell     dirR = [-1, -1, -1, 0, 0, 1, 1, 1]     dirC = [-1, 0, 1, -1, 1, -1, 0, 1]          # Increment area of region by 1     area[0] += 1          # Mark this cell as visited     M[r][c] = 0      # Recur for all connected neighbours     for i in range(8):         new_r = r + dirR[i]         new_c = c + dirC[i]                  if is_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 1s def largest_region(M):   	     # function to find area of the largest region of 1s     rows = len(M)     cols = len(M[0])          # Initialize result as 0 and traverse through the     # all cells of given matrix     max_area = 0     for i in range(rows):         for j in range(cols):             # If a cell with value 1 is found             if M[i][j] == 1:                              	# area is taken as a list of size 1 to                  # achieve pass by reference                 area = [0]                 dfs(M, i, j, rows, cols, area)                                  # maximize the area                  max_area = max(max_area, area[0])          return max_area  if __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 1s using System; using System.Collections.Generic;  class GfG {   	     // A function to check if cell(r, c) can be included in DFS     static bool IsSafe(int[][] M, int r, int c, int rows, int 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 island     static void DFS(int[][] M, int r, int c, int rows,                      				int cols, ref int area) {                	// These arrays are used to get row and column         // numbers of 8 neighbours of a given cell         int[] dirR = { -1, -1, -1, 0, 0, 1, 1, 1 };         int[] dirC = { -1, 0, 1, -1, 1, -1, 0, 1 };          // Increment area of region by 1         area += 1;          // Mark this cell as visited         M[r][c] = 0;          // Recur for all connected neighbours         for (int i = 0; i < 8; i++) {             int newR = r + dirR[i];             int newC = c + dirC[i];              if (IsSafe(M, newR, newC, rows, cols))                 DFS(M, newR, newC, rows, cols, ref area);         }     }      // function to find area of the largest region of 1s     static int LargestRegion(int[][] M) {         int rows = M.GetLength(0);         int cols = M[0].GetLength(0);          // Initialize result as 0 and traverse through the         // all cells of given matrix         int maxArea = 0;         for (int i = 0; i < rows; i++) {             for (int j = 0; j < cols; j++) {                                // If a cell with value 1 is found                 if (M[i][j] == 1) {                     int area = 0;                     DFS(M, i, j, rows, cols, ref area);                      // maximize the area                      maxArea = Math.Max(maxArea, area);                 }             }         }         return maxArea;     }      static void Main() {                int[][] M = {             new int[] { 1, 0, 0, 0, 1, 0, 0 },             new int[] { 0, 1, 0, 0, 1, 1, 1 },             new int[] { 1, 1, 0, 0, 0, 0, 0 },             new int[] { 1, 0, 0, 1, 1, 0, 0 },             new int[] { 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 DFS function isSafe(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 island function DFS(M, r, c, rows, cols, area) { 	     // These arrays are used to get row and column     // numbers of 8 neighbours of a given cell     const dirR = [-1, -1, -1, 0, 0, 1, 1, 1];     const dirC = [-1, 0, 1, -1, 1, -1, 0, 1];      // Increment area of region by 1     area[0] += 1;      // Mark this cell as visited     M[r][c] = 0;      // Recur for all connected neighbours     for (let i = 0; i < 8; i++) {         const newR = r + dirR[i];         const newC = 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 1s function largestRegion(M) {     const rows = M.length;     const cols = M[0].length;      // Initialize result as 0 and traverse through the     // all cells of given matrix     let maxArea = 0;     for (let i = 0; i < rows; i++) {         for (let j = 0; j < cols; j++) {             // If a cell with value 1 is found             if (M[i][j] === 1) {                          	// area is taken as list to achieve                  // pass by reference                 let area = [0];                 DFS(M, i, j, rows, cols, area);                  // Maximize the area                  maxArea = Math.max(maxArea, area[0]);             }         }     }     return maxArea; }  // Example usage const 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] ];  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> using namespace std;  // A function to check if cell(r, c) can be included in DFS bool isSafe(vector<vector<int>> &M, int r, int c, int rows, int 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); }  // Breadth-First-Search to visit all cells in the current island int BFS(vector<vector<int>> &M, int r, int c, int rows, int cols) {      // These arrays are used to get row and column     // numbers of 8 neighbours of a given cell     vector<int> dirR = {-1, -1, -1, 0, 0, 1, 1, 1};     vector<int> dirC = {-1, 0, 1, -1, 1, -1, 0, 1};      int area = 0;      // create a queue for bfs traversal     queue<pair<int, int>> q;      // Push the cell(r, c) into queue and mark it as visited     q.push({r, c});     M[r][c] = 0;     while (!q.empty()) {         pair<int, int> curr = q.front();         q.pop();       	       	// Increment the area of region       	area += 1;        	// Recur for all 8 connected neighbours         for (int i = 0; i < 8; i++) {             int newR = curr.first + dirR[i];             int newC = curr.second + dirC[i];              if (isSafe(M, newR, newC, rows, cols)) {             	M[newR][newC] = 0;               	q.push({newR, newC});             }         }     }     return area; }   // function to find area of the largest region of 1s int largestRegion(vector<vector<int>> &M) {   	int rows = M.size(), cols = M[0].size();        // Initialize result as 0 and traverse through the     // all cells of given matrix     int maxArea = 0;     for (int i = 0; i < rows; i++) {         for (int j = 0; j < cols; j++) {           	             // If a cell with value 1 is found             if (M[i][j] == 1) {                 int area = BFS(M, i, j, rows, cols);                  // maximize the area                  maxArea = max(maxArea, area);             }         }     }     return maxArea; }  int main() {     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);      return 0; } 
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 integers struct Pair {     int row, col; };  int isSafe(int M[MAX_ROWS][MAX_COLS], int r, int c, int rows, int 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); }  // Breadth-First-Search to visit all cells in the current island int BFS(int M[MAX_ROWS][MAX_COLS], int r, int c, int rows, int cols) {   	     // These arrays are used to get row and column numbers of    	// 8 neighbours of a given cell     int dirR[] = {-1, -1, -1, 0, 0, 1, 1, 1};     int dirC[] = {-1, 0, 1, -1, 1, -1, 0, 1};      int area = 0;      // Create a queue for BFS traversal     struct Pair queue[MAX_QUEUE_SIZE];     int front = 0, rear = 0;      // Push the cell(r, c) into queue and mark it as visited     queue[rear++] = (struct Pair){r, c};     M[r][c] = 0;      while (front < rear) {         struct Pair curr = queue[front++];          // Increment the area of region         area += 1;          // Recur for all 8 connected neighbours         for (int i = 0; i < 8; i++) {             int newR = curr.row + dirR[i];             int newC = curr.col + dirC[i];              if (isSafe(M, newR, newC, rows, cols)) {                 M[newR][newC] = 0;                 queue[rear++] = (struct Pair){newR, newC};             }         }     }     return area; }  // Function to find the area of the largest region of 1s int largestRegion(int M[MAX_ROWS][MAX_COLS], int rows, int cols) {   	     // Initialize result as 0 and traverse through all cells    	// of the given matrix     int maxArea = 0;     for (int i = 0; i < rows; i++) {         for (int j = 0; j < cols; j++) {           	             // If a cell with value 1 is found             if (M[i][j] == 1) {                 int area = BFS(M, i, j, rows, cols);                  // Maximize the area                 if (area > maxArea) {                     maxArea = area;                 }             }         }     }     return maxArea; }  int main() {     // Define the matrix directly     int M[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}     };      int rows = 5, cols = 7; // Matrix dimensions      printf("%d\n", largestRegion(M, rows, cols));      return 0; } 
Java
// Java Program to find area of the largest region of 1s  import java.util.LinkedList; import java.util.Queue;  public class GfG {      // A function to check if cell(r, c) can be included in BFS     static boolean isSafe(int[][] M, int r, int c, int rows, int 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);     }      // Breadth-First-Search to visit all cells in the current island     static int BFS(int[][] M, int r, int c, int rows, int cols) {         // These arrays are used to get row and column         // numbers of 8 neighbours of a given cell         int[] dirR = {-1, -1, -1, 0, 0, 1, 1, 1};         int[] dirC = {-1, 0, 1, -1, 1, -1, 0, 1};          int area = 0;          // Create a queue for BFS traversal         Queue<int[]> q = new LinkedList<>();          // Push the cell(r, c) into queue and mark it as visited         q.add(new int[]{r, c});         M[r][c] = 0;                  while (!q.isEmpty()) {             int[] curr = q.poll();             int currR = curr[0];             int currC = curr[1];                          // Increment the area of region             area += 1;              // Recur for all 8 connected neighbours             for (int i = 0; i < 8; i++) {                 int newR = currR + dirR[i];                 int newC = currC + dirC[i];                  if (isSafe(M, newR, newC, rows, cols)) {                     M[newR][newC] = 0;                     q.add(new int[]{newR, newC});                 }             }         }         return area;     }      // Function to find area of the largest region of 1s     static int largestRegion(int[][] M) {         int rows = M.length;         int cols = M[0].length;          // Initialize result as 0 and traverse through the         // all cells of given matrix         int maxArea = 0;         for (int i = 0; i < rows; i++) {             for (int j = 0; j < cols; j++) {                                  // If a cell with value 1 is found                 if (M[i][j] == 1) {                     int area = BFS(M, i, j, rows, cols);                      // Maximize the area                      maxArea = Math.max(maxArea, area);                 }             }         }         return maxArea;     }      public static void main(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  from collections import deque  # A function to check if cell(r, c) can be included in BFS def isSafe(M, r, c, rows, cols):   	     # row number is in range, column number is in range and     # value is 1     return (r >= 0 and r < rows) and (c >= 0 and c < cols) and (M[r][c] == 1)  # Breadth-First-Search to visit all cells in the current island def BFS(M, r, c, rows, cols):   	     # These arrays are used to get row and column     # numbers of 8 neighbours of a given cell     dirR = [-1, -1, -1, 0, 0, 1, 1, 1]     dirC = [-1, 0, 1, -1, 1, -1, 0, 1]      area = 0      # create a queue for bfs traversal     q = deque()      # Push the cell(r, c) into queue and mark it as visited     q.append((r, c))     M[r][c] = 0     while q:         curr = q.popleft()                  # Increment the area of region         area += 1          # Recur for all 8 connected neighbours         for i in range(8):             newR = curr[0] + dirR[i]             newC = curr[1] + dirC[i]              if isSafe(M, newR, newC, rows, cols):                 M[newR][newC] = 0                 q.append((newR, newC))          return area  # Function to find area of the largest region of 1s def largestRegion(M):     rows = len(M)     cols = len(M[0])        # Initialize result as 0 and traverse through the     # all cells of given matrix     maxArea = 0     for i in range(rows):         for j in range(cols):                          # If a cell with value 1 is found             if M[i][j] == 1:                 area = BFS(M, i, j, rows, cols)                  # Maximize the area                  maxArea = max(maxArea, area)          return maxArea  if __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 1s  using System; using System.Collections.Generic;  class GfG {   	     // A function to check if cell(r, c) can be included in BFS     static bool IsSafe(int[][] M, int r, int c, int rows, int 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);     }      // Breadth-First-Search to visit all cells in the current island     static int BFS(int[][] M, int r, int c, int rows, int cols) {                // These arrays are used to get row and column numbers of 8 neighbors of a given cell         int[] dirR = {-1, -1, -1, 0, 0, 1, 1, 1};         int[] dirC = {-1, 0, 1, -1, 1, -1, 0, 1};          int area = 0;          // Create a queue for BFS traversal         Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>();          // Push the cell(r, c) into queue and mark it as visited         q.Enqueue(Tuple.Create(r, c));         M[r][c] = 0;          while (q.Count > 0) {             var curr = q.Dequeue();             int currR = curr.Item1;             int currC = curr.Item2;              // Increment the area of region             area += 1;              // Recur for all 8 connected neighbors             for (int i = 0; i < 8; i++) {                 int newR = currR + dirR[i];                 int newC = currC + dirC[i];                  if (IsSafe(M, newR, newC, rows, cols)) {                     M[newR][newC] = 0;                     q.Enqueue(Tuple.Create(newR, newC));                 }             }         }         return area;     }      // Function to find area of the largest region of 1s     static int LargestRegion(int[][] M) {         int rows = M.Length;         int cols = M[0].Length;          // Initialize result as 0 and traverse through all cells of given matrix         int maxArea = 0;         for (int i = 0; i < rows; i++) {             for (int j = 0; j < cols; j++) {                 // If a cell with value 1 is found                 if (M[i][j] == 1) {                     int area = BFS(M, i, j, rows, cols);                      // Maximize the area                      maxArea = Math.Max(maxArea, area);                 }             }         }         return maxArea;     }      static void Main() {         int[][] M = {             new int[] {1, 0, 0, 0, 1, 0, 0},             new int[] {0, 1, 0, 0, 1, 1, 1},             new int[] {1, 1, 0, 0, 0, 0, 0},             new int[] {1, 0, 0, 1, 1, 0, 0},             new int[] {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 BFS function isSafe(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); }  // Breadth-First-Search to visit all cells in the current island function BFS(M, r, c, rows, cols) {      // These arrays are used to get row and column numbers      // of 8 neighbors of a given cell     const dirR = [-1, -1, -1, 0, 0, 1, 1, 1];     const dirC = [-1, 0, 1, -1, 1, -1, 0, 1];      let area = 0;      // Create a queue for BFS traversal     const queue = [];      // Push the cell(r, c) into queue and mark it as visited     queue.push([r, c]);     M[r][c] = 0;      while (queue.length > 0) {         const [currR, currC] = queue.shift();          // Increment the area of region         area += 1;          // Recur for all 8 connected neighbors         for (let i = 0; i < 8; i++) {             const newR = currR + dirR[i];             const newC = currC + dirC[i];              if (isSafe(M, newR, newC, rows, cols)) {                 M[newR][newC] = 0;                 queue.push([newR, newC]);             }         }     }      return area; }  // Function to find area of the largest region of 1s function largestRegion(M) {     const rows = M.length;     const cols = M[0].length;      let maxArea = 0;     for (let i = 0; i < rows; i++) {         for (let j = 0; j < cols; j++) {             // If a cell with value 1 is found             if (M[i][j] === 1) {                 const area = BFS(M, i, j, rows, cols);                  // Maximize the area                 maxArea = Math.max(maxArea, area);             }         }     }      return maxArea; }  const 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] ];  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). 


Next Article
Max Area of Island - Largest in Boolean Matrix

N

Nishant Singh
Improve
Article Tags :
  • Graph
  • DSA
  • Microsoft
  • Amazon
  • Samsung
  • BFS
  • DFS
Practice Tags :
  • Amazon
  • Microsoft
  • Samsung
  • BFS
  • DFS
  • Graph

Similar Reads

    Depth First Search or DFS for a Graph
    In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
    13 min read

    DFS in different language

    C Program for Depth First Search or DFS for a Graph
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS tr
    4 min read
    Depth First Search or DFS for a Graph - Python
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a Boolean visited array. A graph can have more than one DFS tr
    4 min read
    Java Program for Depth First Search or DFS for a Graph
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Prerequisite: Graph knowledge is important to understand the concept of DFS. What is DFS?DFS or Depth First Traversal is the traversing algorithm. DFS can be used to approach the elements of a Graph. To avoid p
    3 min read
    Iterative Depth First Traversal of Graph
    Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
    10 min read
    Applications, Advantages and Disadvantages of Depth First Search (DFS)
    Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
    4 min read
    Difference between BFS and DFS
    Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
    2 min read
    Depth First Search or DFS for disconnected Graph
    Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Disconnected Graph Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given sour
    7 min read
    Printing pre and post visited times in DFS of a graph
    Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored
    8 min read
    Tree, Back, Edge and Cross Edges in DFS of Graph
    Given a directed graph, the task is to identify tree, forward, back and cross edges present in the graph.Note: There can be multiple answers.Example:Input: GraphOutput:Tree Edges: 1->2, 2->4, 4->6, 1->3, 3->5, 5->7, 5->8 Forward Edges: 1->8 Back Edges: 6->2 Cross Edges: 5-
    9 min read
    Transitive Closure of a Graph using DFS
    Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
    8 min read

    Variations of DFS implementations

    Implementation of DFS using adjacency matrix
    Depth First Search (DFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (wh
    8 min read
    Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
    We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and
    7 min read
    Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
    In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph. Undirected Weighted Graph We use two STL containers to represent graph: vector : A sequence container. Here we use i
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences