Graph BFS/DFS

Trees & Graphs

Signal

Islands/regions in a grid, shortest steps

Template

Flood-fill with a visited set; BFS for shortest.

Worked example (1)

#13

Graph BFS/DFS (grid)

Graph DFS

Given a grid of '1' (land) and '0' (water), count the islands (groups of land connected horizontally/vertically).

function numIslands(grid: string[][]): number {
  const rows = grid.length, cols = grid[0]?.length ?? 0;
  let count = 0;
  const sink = (r: number, c: number): void => {
    if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] !== '1') return;
    grid[r][c] = '0'; // mark visited in place
    sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
  };
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++)
      if (grid[r][c] === '1') { count++; sink(r, c); }
  return count;
}
Insight

Each "1" you reach from a new start is one island; sinking prevents double-counting.