Code Logo

Max Area of Island

Published at25 Jul 2026
DFS Medium 2 views
Like0

Given a 2D grid where 1 represents land and 0 represents water, find the maximum area of an island. An island is a group of connected 1s adjacent horizontally or vertically. The area is the number of 1s in the island.

For example, a grid with a 2-cell island and a 4-cell island returns 4. A grid with no land returns 0. A grid entirely filled with 1s returns the total cell count.

This problem teaches grid-based DFS/BFS traversal. It is a classic graph problem that combines component counting with area computation. Each island is a connected component in the grid graph.

The solution iterates through each cell. When land is found, perform DFS to explore the entire island, counting cells. Track the maximum area seen across all islands.

Edge cases include an empty grid (return 0), all water (return 0), a single-cell island (return 1), and the entire grid being one large island.

Example Input & Output

Example 1
Input
[["0"]]
Output
0
Explanation

No land

Example 2
Input
[["1"]]
Output
1
Explanation

Single cell

Example 3
Input
[["1","1"],["1","1"]]
Output
4
Explanation

2x2 island

Example 4
Input
[["0","0","0"],["0","0","0"]]
Output
0
Explanation

No land

Example 5
Input
[["0","0","1","0","0","0","0","1","0","0","0","0","0"],["0","0","0","0","0","0","0","1","1","1","0","0","0"],["0","1","1","0","1","0","0","0","0","0","0","0","0"],["0","1","0","0","1","1","0","0","1","0","1","0","0"],["0","1","0","0","1","1","0","0","1","1","1","0","0"],["0","0","0","0","0","0","0","0","0","0","1","0","0"],["0","0","0","0","0","0","0","1","1","1","0","0","0"],["0","0","0","0","0","0","0","1","1","0","0","0","0"]]
Output
6
Explanation

Max area is 6 (the island in top-right)

Algorithm Flow

Recommendation Algorithm Flow for Max Area of Island

Solution Approach

Use DFS to explore each island and compute its area, tracking the maximum.

function maxArea(grid)
  maxArea = 0
  for r = 0 to rows - 1
    for c = 0 to cols - 1
      if grid[r][c] == 1
        area = dfs(r, c)
        if area > maxArea then maxArea = area
  return maxArea

Iterate through each cell. When land (1) is found, perform DFS to compute the island's area, marking visited cells as 0 to avoid revisiting. Track the maximum area encountered. Return the maximum.

Time complexity is O(rows * cols), space complexity is O(rows * cols) worst case for the recursion stack.

Best Answers

java
class Solution {
    int r,c;
    public int solution(String[][] g) {
        if(g==null||g.length==0)return 0;r=g.length;c=g[0].length;int mx=0;
        for(int i=0;i<r;i++)for(int j=0;j<c;j++)if(g[i][j].equals("1"))mx=Math.max(mx,dfs(g,i,j));
        return mx;
    }
    int dfs(String[][] g,int i,int j){
        if(i<0||i>=r||j<0||j>=c||g[i][j].equals("0"))return 0;
        g[i][j]="0";return 1+dfs(g,i-1,j)+dfs(g,i+1,j)+dfs(g,i,j-1)+dfs(g,i,j+1);
    }
}