VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-length-largest-region-boolean-matrix/

⇱ Max Area of Island - Largest in Boolean Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Area of Island - Largest in Boolean Matrix

Last Updated : 23 Jul, 2025

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:
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:


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:


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). 

Comment
Article Tags: