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