Breadth-first search
Breadth-first search explores a graph in rings of increasing distance using a queue. Watch the frontier expand level by level.
Before you start: Queues: enqueue, dequeue; circular buffer, Level-order traversal.
The idea
Drop a stone in a pond and ripples spread in rings. Breadth-first search explores a graph the same way.
Each ring holds the nodes that are the same number of edges from the start. The search finishes one ring before it begins the next.
Intuition
Level 0 is the start. Level 1 holds its neighbors, level 2 their new neighbors, and so on.
A queue keeps the rings in order. Nodes found earlier are served earlier, so ring 2 waits until ring 1 is done.
Complexity
BFS looks at each edge a constant number of times: O(V + E). The rescan curve rescans every edge for every node: V × E.
Rescanning means looking at all edges again each time a node is taken. The queue and the level table make one pass enough.
Space is O(V). The queue and the level table each hold at most one entry per node.
Pitfalls
Mark a node as seen when it joins the queue. Marked only on leaving, node 3 (crossed out) joins twice.
BFS only reaches nodes connected to the start, so crossed-out 3 and 4 stay unseen. Start again from each unseen node.
Variations
On a grid, each open cell is a node and its open neighbors are edges. BFS gives the shortest route around the walls.
Put several sources in the queue at level 0. Every node then gets its distance to the nearest source.
Code
Pseudocode
bfs(graph, source)
level[source] ← 0
queue ← [source]
while queue is not empty
u ← remove the front of queue
for each neighbor v of u
if v has no level
level[v] ← level[u] + 1
add v to the back of queue
return level
Python
from collections import deque
def bfs(adj, source):
level = {source: 0}
queue = deque([source])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in level:
level[v] = level[u] + 1
queue.append(v)
return level
JavaScript
function bfs(adj, source) {
const level = new Map([[source, 0]]);
const queue = [source];
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
for (const v of adj[u]) {
if (!level.has(v)) {
level.set(v, level.get(u) + 1);
queue.push(v);
}
}
}
return level;
}
Java
static Map<Integer, Integer> bfs(List<List<Integer>> adj, int source) {
Map<Integer, Integer> level = new HashMap<>();
level.put(source, 0);
Deque<Integer> queue = new ArrayDeque<>(List.of(source));
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v : adj.get(u)) {
if (!level.containsKey(v)) {
level.put(v, level.get(u) + 1);
queue.add(v);
}
}
}
return level;
}
Cost at a glance
| Time | O(V + E) |
|---|---|
| Space | O(V) |
| Input | Any graph |
| Output | Visit order and levels from a source |
Practice problems (8)
BFS order Warm-up
Run BFS from node 0 on this graph. A node adds its unseen neighbors to the queue in increasing number order.
First predict which node leaves the queue after node 0, then put all nodes in the order BFS takes them from the queue.
Which structure drives BFS? Warm-up
BFS must finish every node at distance 1 before any node at distance 2. Which data structure holds the waiting nodes?
Cost of BFS on a sparse graph Warm-up
Pick the time and space complexity of this BFS on a connected graph with n nodes and at most 2n edges.
Number of levels Warm-up
Complete countLevels(graph, source). It returns how many levels (rings) BFS finds from source, counting level 0. Only reachable nodes count.
Fill the three blanks.
Implement BFS Standard
Given a graph and a source node, return the nodes reachable from source in the order breadth-first search takes them from the queue.
A node adds its unseen neighbors in increasing node number. Directed graphs follow edge direction. buildAdjacency(graph) returns the adjacency lists.
Fewest edges between two nodes Standard
Return the smallest number of edges on a path from source to target, or -1 if no path exists. Directed graphs follow edge direction. buildAdjacency(graph) returns the adjacency lists.
Spot the bug: when to mark seen Standard
This bfsOrder should list each reachable node once, in BFS order. On graphs with a cycle it lists some nodes twice.
Click the faulty line, then fix the code.
BFS on a grid with walls Challenge
A grid holds 0 for an open cell and 1 for a wall. Starting at the top-left cell, move one step up, down, left or right onto open cells.
Return the fewest steps to reach the bottom-right cell, or -1 if it cannot be reached.
Related topics
Next on the path: Depth-first search