Typorithm · medium

Number of Islands

number-of-islandsgraphsgridflood-filldfs
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Number of Islands

0%

Graphs

Scan the grid; each unvisited land cell starts an island, and a DFS flood-fill sinks its whole connected body.

An island is a maximal group of orthogonally connected land cells.

Scanning the grid, every '1' not yet sunk begins a new island and triggers a flood fill.

The flood fill marks each reached land cell as water so it is never counted twice.

01

Each fresh land cell = +1 island.

02

Flood fill sinks the whole island.

03

Mark visited to prevent recounting.

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

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

  for (let r = 0; r < rows; r += 1) {
    for (let c = 0; c < cols; c += 1) {
      if (grid[r][c] === "1") {
        count += 1;
        sink(r, c);
      }
    }
  }

  return count;
}

Read the implementation

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

1. Stop conditions

Return on out-of-bounds cells or water.

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

2. Sink the cell

Mark visited land as water to avoid recounting.

grid[r][c] = "0"

3. Flood neighbors

Recurse into all four orthogonal directions.

sink(r + 1, c)

4. New island

Each unvisited land cell starts a fresh island.

count += 1

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.

Number of Islands: Lesson & Practice · Typorithm | ApplyDjinn