Skip to content
DSA Patterns
Menu
Language
Grid & Graph BFSLC #2002 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Number of Islands

Problem (restated)

Given a 2D grid of ‘1’ (land) and ‘0’ (water), return the number of islands. An island is max 4-directionally connected land.

Intuition

Each unvisited land cell starts a component. Flood-fill (DFS/BFS) marks the whole island; count how many times you start a fill.

Approaches

DFS flood fill

Unverified
Time O(m·n)Space O(m·n) worst-case stack

Idea. Iterate cells; on land, increment count and DFS to mark all connected land as water/visited.

Walkthrough. Grid with two separate land blobs → count 2.

Trade-offs. DFS is concise; BFS uses explicit queue (safer stack depth on huge grids).

Solution
export function numIslands(grid: string[][]): number {
  if (!grid.length) return 0;
  const m = grid.length, n = grid[0]!.length;
  const dfs = (r: number, c: number) => {
    if (r < 0 || c < 0 || r >= m || c >= n || grid[r]![c] !== "1") return;
    grid[r]![c] = "0";
    dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
  };
  let count = 0;
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      if (grid[r]![c] === "1") { count++; dfs(r, c); }
  return count;
}
export function numIslands(grid: string[][]): number {
  if (!grid.length) return 0;
  const m = grid.length, n = grid[0]!.length;
  const dfs = (r: number, c: number) => {
    if (r < 0 || c < 0 || r >= m || c >= n || grid[r]![c] !== "1") return;
    grid[r]![c] = "0";
    dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
  };
  let count = 0;
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      if (grid[r]![c] === "1") { count++; dfs(r, c); }
  return count;
}

Template connection

Each unvisited '1' starts a component. DFS or BFS marks the whole 4-connected land before the scan moves on. The answer counts those starts.

Reflection

  • A land cell 1 bumps the count, then you mark its neighbors. Without the mark the same island is counted twice.
  • Four directions. A diagonal neighbor is a different island. Check a corner, and a single cell.
  • An empty grid is 0. All water is 0. All land is 1.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Number of islands. 1 is land, 0 is water. Count 4-connected components.

c0c1c2
r0
1
1
0
r1
1
0
0
r2
0
0
1
Stateislands=0

islands = 0

Key:CurrentActive rangeMatchSettledEliminated