↻one more pass.
Graphs · Medium

Max Area of Island: the idea to remember.

Find the largest four directionally connected group of land cells in a binary grid.

Solve on LeetCode ↗

The core insight

Flood fill each unvisited land cell, count its component, and retain the largest area.

Why it works

Each land cell belongs to exactly one connected component and contributes once when marked on discovery.

The mistake to avoid

Use four directions, not diagonals. This implementation marks the input grid as visited.

Time: O(rows · cols)Space: O(rows · cols) worst case recursion

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Flood fill each unvisited land cell, count its component, and retain the largest area.
int maxArea = 0;

public int maxAreaOfIsland(int[][] grid) {
    maxArea = 0; // Reset per call; component searches mutate the grid.
  for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[0].length; j++) {
      maxArea = Math.max(maxArea, 
                  maxAreaOfIsland(grid, i, j));
    }
  }

  return maxArea;
}

public int maxAreaOfIsland(int[][] grid, int r, int c) {
  if (r < 0 || c < 0 || 
      r == grid.length || 
      c == grid[0].length || 
      grid[r][c] == 0) {
        return 0;  
  }

  grid[r][c] = 0;

  return (1 + maxAreaOfIsland(grid, r + 1, c) +
              maxAreaOfIsland(grid, r - 1, c) +
              maxAreaOfIsland(grid, r, c + 1) +
              maxAreaOfIsland(grid, r, c - 1));
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.