Skip to content
ΣDSA Patterns
Menu
Language

Grid & Graph BFS

Guide 2 of 6 · Path 2 of 6

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 8
S
.
.
T
.
#
.
.
.
.
.
.

queue = [S] · dist[S] = 0

Grid BFS: treat each cell as a node; 4-neighbors are edges. Seed the queue at the start.

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

Tested only
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

Grid BFS/DFS connected components.

Reflection