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