Breadth-First Search
How breadth-first search uses a queue to find the fewest-edges path in an unweighted graph or grid, its variants, and what interviewers ask about it.
On this page
Breadth-first search (BFS) is a way to visit every node of a graph in order of its distance from a starting node: first the start, then every node one edge away, then every node two edges away, and so on. Because of that order, the first time BFS reaches a node it has found a path with the fewest edges. You use it whenever a problem asks for the minimum number of steps, moves or hops in a graph where every step costs the same.
Without BFS you would have to compare many routes. A depth-first walk, for example, can reach a node by a long winding route first, and it would have to keep searching to find out whether a shorter one exists. BFS never has that problem, because it only reaches a node by a longer route after it has already reached it by every shorter one.
How BFS works
BFS keeps a queue of nodes that have been discovered but not yet processed. It takes a node from the front of the queue and adds that node's undiscovered neighbours to the back. Because the queue is first in, first out, every node at distance 1 is processed before any node at distance 2, since the distance-2 nodes are only added while processing distance-1 nodes.
A graph can contain cycles (see Graph Basics), so BFS also keeps a set of nodes it has already seen. A node goes into the seen set at the moment it is added to the queue, not when it is taken out.
- Put the start node in the queue, mark it seen, and give it distance 0.
- Take the node at the front of the queue.
- For each neighbour that has not been seen, mark it seen, set its distance to the current node's distance plus 1, and add it to the back of the queue.
- Repeat from step 2 until the queue is empty.
Tracing BFS on a small graph
This is the bus map from Graph Basics, with BFS starting at A and each node's neighbours visited in alphabetical order. The queue is shown under the graph, and each node's distance is written next to it.
queue = [start]; dist[start] = 0while queue is not empty: node = take from the front of queue for each neighbour next of node: if next not seen: dist[next] = dist[node] + 1 add next to the back of queue- queue0A
1Put A in the queue and mark it seen at distance 0. It counts as seen from now on.
- queue0B1C
- visited
- 1
2Take A (d=0) from the queue. Its neighbours B and C are new, so both are added at distance 1.
- queue0C1D
- visited
- 2
3Take B (d=1). Its neighbour D is new and is added at distance 2, and its neighbour A has already been seen, so it is skipped.
- queue0D1E
- visited
- 3
4Take C (d=1). E is new and is added at distance 2. A and D have already been seen, so they are skipped.
- queue0E1F
- visited
- 4
5Take D (d=2). F is new and is added at distance 3, and B and C have already been seen.
- queue0F
- visited
- 5
6Take E (d=2). Both of its neighbours, C and F, have already been seen, so nothing is added.
- queue0G
- visited
- 6
7Take F (d=3). G is new and is added at distance 4, and D and E have already been seen.
- queue
- visited
- 7
8Take G (d=4). Its only neighbour F has already been seen, so nothing is added.
- queue
- visited
- 7
9The queue is empty, so every stop now has its fewest-stops distance. G is 4 stops from A, by way of B, D and F.
Code
The code below also stores each node's parent, which is the node it was discovered from. To recover the route to a goal, follow the parents from the goal back to the start and reverse the result.
// graph: adjacency list, e.g. { A: ["B", "C"], B: ["A", "D"], ... }
function bfs(graph, start) {
const dist = { [start]: 0 }; // also our "seen" set
const parent = { [start]: null };
const queue = [start];
let head = 0; // index of the front: O(1) dequeue
while (head < queue.length) {
const node = queue[head++];
for (const next of graph[node]) {
if (next in dist) continue; // already seen
dist[next] = dist[node] + 1;
parent[next] = node;
queue.push(next);
}
}
return { dist, parent };
}
function pathTo(parent, goal) {
if (!(goal in parent)) return null; // unreachable
const path = [];
for (let at = goal; at !== null; at = parent[at]) path.push(at);
return path.reverse();
}
// pathTo(bfs(graph, "A").parent, "G") → ["A", "B", "D", "F", "G"]from collections import deque
# graph: adjacency list, e.g. {"A": ["B", "C"], "B": ["A", "D"], ...}
def bfs(graph, start):
dist = {start: 0} # also our "seen" set
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt in dist:
continue # already seen
dist[nxt] = dist[node] + 1
parent[nxt] = node
queue.append(nxt)
return dist, parent
def path_to(parent, goal):
if goal not in parent:
return None # unreachable
path = []
at = goal
while at is not None:
path.append(at)
at = parent[at]
return path[::-1]
# path_to(bfs(graph, "A")[1], "G") → ['A', 'B', 'D', 'F', 'G']Cost of BFS
Each node joins the queue at most once, and each neighbour list is read once, so every edge is looked at twice in an undirected graph. The queue, dist and parent hold at most V entries.
BFS on a grid
Finding the fewest moves through a maze is the same problem, since a grid is a graph in which each open cell is connected to its open neighbours above, below, left and right (see Graph Basics). There is no adjacency list. You compute the neighbours from the row and column, and you skip any that are outside the grid or are walls. Instead of a dist map, use a 2D array of the same size as the grid, filled with -1 to mean "not seen yet".
- steps from start
0 1 2 3 4 0 0 # 1 # 2 # # 3 # G - distance
- 0
- cells reached
- 1
1The search starts at the top-left cell with distance 0. Cells marked # are walls, which are not part of the graph.
- steps from start
0 1 2 3 4 0 0 1 # 1 1 # 2 # # 3 # G - distance
- 1
- cells reached
- 3
2Wave 1 contains the cells to the right of and below the start. The cells above and to the left are outside the grid.
- steps from start
0 1 2 3 4 0 0 1 2 # 1 1 # 2 2 # # 3 # G - distance
- 2
- cells reached
- 5
3Wave 2 continues along the top row and down the left column, because the wall in column 1 blocks the middle.
- steps from start
0 1 2 3 4 0 0 1 2 # 1 1 # 3 2 2 # # 3 3 # G - distance
- 3
- cells reached
- 7
4Wave 3 continues down the left column and starts into the middle of the grid.
- steps from start
0 1 2 3 4 0 0 1 2 # 1 1 # 3 4 2 2 # 4 # 3 3 4 # G - distance
- 4
- cells reached
- 10
5Wave 4 contains (1, 3), (2, 2) and (3, 1).
- steps from start
0 1 2 3 4 0 0 1 2 # 1 1 # 3 4 5 2 2 # 4 # 3 3 4 5 # G - distance
- 5
- cells reached
- 12
6Wave 5 contains (1, 4) and (3, 2). Whichever of its two neighbours is processed first claims (3, 2), and the other skips it.
- steps from start
0 1 2 3 4 0 0 1 2 # 6 1 1 # 3 4 5 2 2 # 4 # 6 3 3 4 5 # G - distance
- 6
- cells reached
- 14
7Wave 6 fills the right-hand column above and below (1, 4).
- steps from start
0 1 2 3 4 0 0 1 2 # 6 1 1 # 3 4 5 2 2 # 4 # 6 3 3 4 5 # 7 - distance
- 7
- cells reached
- 15
8Wave 7 reaches the exit G. Cells leave the queue in order of distance, so no shorter route exists.
- steps from start
0 1 2 3 4 0 0 1 2 # 6 1 1 # 3 4 5 2 2 # 4 # 6 3 3 4 5 # 7 - answer
- 7
- cells reached
- 15
9The answer is 7 steps.
const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
// grid: array of strings, "#" is a wall. Start top-left, exit bottom-right.
function stepsToExit(grid) {
const rows = grid.length, cols = grid[0].length;
const dist = grid.map((row) => new Array(row.length).fill(-1));
dist[0][0] = 0;
const queue = [[0, 0]];
let head = 0;
while (head < queue.length) {
const [r, c] = queue[head++];
if (r === rows - 1 && c === cols - 1) return dist[r][c];
for (const [dr, dc] of DIRS) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
if (grid[nr][nc] === "#" || dist[nr][nc] !== -1) continue;
dist[nr][nc] = dist[r][c] + 1;
queue.push([nr, nc]);
}
}
return -1; // the exit cannot be reached
}
stepsToExit(["...#.", ".#...", ".#.#.", "...#."]); // 7from collections import deque
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# grid: list of strings, "#" is a wall. Start top-left, exit bottom-right.
def steps_to_exit(grid):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
dist[0][0] = 0
queue = deque([(0, 0)])
while queue:
r, c = queue.popleft()
if (r, c) == (rows - 1, cols - 1):
return dist[r][c]
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == "#" or dist[nr][nc] != -1:
continue
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return -1 # the exit cannot be reached
steps_to_exit(["...#.", ".#...", ".#.#.", "...#."]) # 7A grid with R rows and C columns has R × C cells and each has at most 4 neighbours, so the time and the space are both O(R × C).
Variants
Starting from several nodes at once
To find how far each cell is from the nearest one of several sources, such as the nearest exit, fire or hospital, put all the sources in the queue at distance 0 before the loop starts. The waves then grow from every source at the same time, and each cell is claimed by whichever source is closest. This is one BFS instead of one per source, so the cost stays O(V + E) however many sources there are. Problems such as "how many minutes until every orange has rotted" work this way.
Level by level
Sometimes the answer is the number of waves rather than a distance for each node, or you need to handle one wave at a time, as in "return the values of a tree row by row". Take the queue's current length at the start of each outer iteration, process exactly that many nodes, and then increase a level counter. Nodes added during the iteration belong to the next wave and are not processed until the next iteration. This replaces the dist array when only the number of levels matters.
Searching a graph that is never written down
Many BFS problems have no graph in the input. Each state of a puzzle or a word is a node, and the allowed moves define the edges. In word ladder problems the nodes are words and two words are connected if they differ by one letter. In a sliding-tile puzzle or a lock with four rotating wheels, a node is a whole arrangement and an edge is one move. You generate a node's neighbours when you take it from the queue, and the seen set holds the states already generated, usually as strings or tuples. The cost is the number of reachable states, which can be large, so state the size of the state space when you give the complexity.
Searching from both ends
If you know both the start and the goal, you can run one BFS from each and stop when the two searches meet. When each node has about b neighbours and the shortest path has d edges, a single search reaches roughly b to the power d nodes, while two searches that each go half way reach about twice b to the power d/2. This helps a lot on large implicit graphs such as word ladders, and it needs edges that can be followed in both directions.
When BFS does not apply
BFS counts edges, so it is only correct when every edge costs the same. If edges have different costs, such as roads of 2 and 30 minutes, the path with the fewest roads can be the slowest. Use Dijkstra's algorithm for non-negative weights. If the weights are only 0 and 1, a variant called 0-1 BFS keeps a double-ended queue, putting 0-cost neighbours at the front and 1-cost neighbours at the back, and runs in O(V + E).
For "is this reachable?" and "how many connected pieces are there?", BFS works, but depth-first search is just as correct and shorter to write recursively. BFS is the wrong tool when you need every path, or need to explore one branch completely before trying another, as in backtracking.
Pitfalls
In the interview
The signals that a problem needs BFS are a request for the minimum number of steps, moves, hops, turns or operations, where every step costs the same, and a structure that is a graph, a grid or a set of states connected by moves. Phrases such as "shortest path", "nearest", "fewest moves" and "minimum number of mutations" all point to it. Problems that ask for the values of a tree level by level also use it. Say which node or state is the vertex and what an edge is, because that is the first thing the interviewer checks.
Questions to expect:
- "Why does BFS find the shortest path?" It takes nodes from the queue in order of distance from the start, because nodes at distance k are all added before any node at distance k + 1. So the first time a node is reached, no shorter route exists. This only holds when all edges cost the same.
- "What if the edges have weights?" BFS is no longer correct. Use Dijkstra's algorithm for non-negative weights. If the weights are only 0 and 1, use 0-1 BFS with a double-ended queue.
- "How do you return the path and not just its length?" Store each node's parent when you add it to the queue. When you reach the goal, follow the parents back to the start and reverse the list.
- "What are the time and space complexity?" O(V + E) time and O(V) space with adjacency lists, or O(R × C) on a grid. With an adjacency matrix, finding a node's neighbours takes O(V), so the time becomes O(V²).
- "BFS or DFS here?" Choose BFS when the answer depends on the shortest distance. Choose DFS when you only need to know whether something is reachable or to count components. DFS uses less memory on a wide, shallow graph, because BFS has to hold a whole wave in the queue.
Graph: { P: [Q, R], Q: [P, S], R: [P, S, T], S: [Q, R], T: [R] }. In what order does BFS from P take nodes out of the queue?
Why does BFS mark a node seen when it joins the queue instead of when it leaves?
A grid is 1,000 × 1,000. At most how many cells does BFS take out of the queue?
Roads between towns have different travel times. Which algorithm finds the fastest route from one town?
What to practise next
Depth-first search explores one branch as far as it goes before backing up, which makes it the simpler choice for connectivity and counting components. For graphs with weighted edges, continue with Dijkstra's algorithm.