Code Logo

Max Area of Island

Published at25 Jul 2026
DFS Medium 0 views
Like0

You are given a 2D grid containing '1' (land) and '0' (water). Find the maximum area of an island. An island is formed by connecting adjacent land cells horizontally or vertically.

Use DFS to explore each island. When a '1' is found, compute its area via DFS by counting all connected land cells, then mark them as visited. Track the maximum area found.

Time is O(m*n) and space is O(m*n) for the recursion stack.

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
Recommendation Algorithm Flow for Max Area of Island

Solution Approach

function solution(grid) {
  var rows = grid.length, cols = grid[0].length, maxArea = 0;
  function dfs(i, j) {
    if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] === '0') return 0;
    grid[i][j] = '0';
    return 1 + dfs(i-1,j) + dfs(i+1,j) + dfs(i,j-1) + dfs(i,j+1);
  }
  for (var i = 0; i < rows; i++) {
    for (var j = 0; j < cols; j++) {
      if (grid[i][j] === '1') { var area = dfs(i, j); if (area > maxArea) maxArea = area; }
    }
  }
  return maxArea;
}

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);
    }
}