Algorithm patterns← All patterns

Pattern 05 / 10 · Fundamentals

BFS / DFS

Explore a grid or graph one neighbour at a time and mark where you have been.

The idea

From a starting cell, keep a queue (BFS) or a stack (DFS) of places to visit. Pop one, look at its neighbours, push the ones you have not visited yet and mark them. When the queue is empty, the whole connected region has been found.

time O(rows × cols)space O(rows × cols) in the worst case

Reach for it when

  • The input is a grid, a tree or a graph of connected things.
  • You need to count connected regions or flood-fill an area.
  • BFS: the shortest path in an unweighted graph. DFS: explore every branch.

Watch it run

200. Number of Islands

Count the islands: groups of '1' cells connected up, down, left or right.

Example 1

Input: grid = ["11110", "11010", "11000", "00000"]

Output: 1

Example 2

Input: grid = ["11000", "11000", "00100", "00011"]

Output: 3

WALKTHROUGH INPUT · grid = ["11000", "11010", "00100", "00011"]

1
1
~
~
~
1
1
~
1
~
~
~
1
~
~
~
~
~
1
1

queue

empty
islands = 0

Scan the grid cell by cell. count = 0.

1 / 34
solution.ts
1function numIslands(grid: string[][]): number {
2 let count = 0;
3 for (let r = 0; r < grid.length; r++) {
4 for (let c = 0; c < grid[0].length; c++) {
5 if (grid[r][c] !== "1") continue;
6 count++;
7 const queue = [[r, c]]; grid[r][c] = "0";
8 while (queue.length) {
9 const [y, x] = queue.shift()!;
10 for (const [ny, nx] of neighbours(y, x)) {
11 if (grid[ny]?.[nx] !== "1") continue;
12 grid[ny][nx] = "0"; queue.push([ny, nx]);
13 }
14 }
15 }
16 }
17 return count;
18}

Practice next