Typorithm · medium

Max Area of Island

max-area-of-islandgraphsgridflood-fillaccumulate
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Max Area of Island

0%

Graphs

Flood-fill each island while summing its cells, and keep the maximum area across all islands.

Like counting islands, but each flood fill returns the island's area instead of just marking it.

Area is one for the current cell plus the areas returned from its four neighbors.

The outer scan keeps the largest area produced by any starting cell.

01

Return 1 + four neighbor areas.

02

Sink cells to count once.

03

Track the running maximum.

function maxAreaOfIsland(grid) {
  const rows = grid.length;
  const cols = grid[0].length;
  let best = 0;

  function area(r, c) {
    if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
      return 0;
    }
    grid[r][c] = 0;
    return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1);
  }

  for (let r = 0; r < rows; r += 1) {
    for (let c = 0; c < cols; c += 1) {
      if (grid[r][c] === 1) {
        best = Math.max(best, area(r, c));
      }
    }
  }

  return best;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Empty contributes 0

Out-of-bounds or water adds no area.

if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
      return 0;
    }

2. Mark visited

Sink the cell so it is counted once.

grid[r][c] = 0

3. Sum the body

This cell plus the four neighbor areas is the island size.

return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)

4. Track maximum

Keep the largest island area found.

best = Math.max(best, area(r, c))

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Max Area of Island: Lesson & Practice · Typorithm | ApplyDjinn