Max Area of Island

Program for having Max Area of Island

You are given a grid represented as a matrix where each cell is either 0 (water) or 1 (land).

An island is a group of 1’s connected horizontally or vertically. The grid edges are surrounded by water.

The area of an island is the count of cells within it. Return the largest island area in the grid. If no islands exist, return 0.

Max Area of Island

Example 1:

Example of Maximum area of Island

Explanations : 

  • 1’s cannot be connected diagonally, so the maximum area of the island is 6.

Constraints:

  • 1 <= grid.length, grid[i].length <= 50

Solution for having Max Area of Island

Recommendation for Time and Space Complexity – Aim for O(m * n) time and space complexity, where m is the number of rows and n is the number of columns.

Hints for solving problems

Hint 1

An island is a group of connected 1’s. Can you find all such groups by visiting each only once, perhaps using recursion?

Hint 2

Use Depth First Search (DFS) to explore each group. Start from a 1 and recursively visit all connected 1’s. How can you calculate the island’s area during this?

Hint 3

Traverse the grid. When you find a 1, start a DFS, mark visited cells as 0, and count the area. After each DFS, update the maximum area. Return the largest area after checking the entire grid.

There are mainly 3 approach to solve this problem-

  1. Depth First Search Method
  2. Breadth First Search Method
  3. Disjoint Set Union Method

1. Depth First Method

This approach uses recursion to explore all connected 1’s starting from a cell. By marking visited cells as 0, it calculates the area of an island while traversing the grid.

  • Time complexity: O(m * n)
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns in the grid.

Code

 

2. Breadth First Search Method

This method uses a queue to iteratively explore all connected 1’s layer by layer. It calculates the island’s area while marking cells as visited during the traversal.

  • Time complexity: O(m*n)
  • Space complexity: O(m*n)

where m is the number of rows and n is the number of columns in the grid.

Code

3. Disjoint Set Union Method

This approach treats the grid as a graph and uses the Union-Find technique to group connected 1’s into sets. The size of the largest set gives the maximum island area.

  • Time complexity: O(m * n).
  • Space complexity: O(m * n).

where m is the number of rows and n is the number of columns in the grid.

Code

More Articles