Shortest paths in unweighted graphs; path reconstruction
In an unweighted graph BFS finds shortest paths. Distance labels spread outward and parent arrows trace each path back to the source.
The idea
A map has a start and a goal. Which route uses the fewest edges, and which stops does it pass?
When every edge counts the same, "shortest" means "fewest edges". BFS answers that for every node at once.
Intuition
BFS reaches nodes ring by ring. The ring number of a node is its fewest edges from the start.
Each node also remembers its parent, the node that found it first. Following parents leads back to the start.
Complexity
One BFS checks each edge a constant number of times: O(V + E). A new search for every target would cost about V × E.
Running a new search for every target would repeat the same work. One search from the source serves all targets.
Space is O(V). The parent array shown here, the distance table and the queue each hold at most one entry per node.
Pitfalls
BFS counts edges, not weights. Its one-edge path 0-1 costs 10, while 0, 2, 1 costs only 2.
The target 4 sits in another part, so it never gets a distance. Return an empty path before reading its parent.
Variations
A maze is a graph: open cells are nodes and open neighbors are edges. The first border cell BFS takes is the nearest exit.
Words are nodes, joined when one letter apart. BFS labels each word with its steps from hit: the ladder to cog takes 4.
Code
Pseudocode
shortestPath(graph, source, target)
dist[source] ← 0; parent[source] ← none
queue ← [source]
while queue is not empty
u ← remove the front of queue
for each neighbor v of u
if v has no dist
dist[v] ← dist[u] + 1
parent[v] ← u
add v to the back of queue
if target has no dist: return []
path ← []
for v ← target; v ≠ none; v ← parent[v]
add v to the front of path
return path
Python
from collections import deque
def shortest_path(adj, source, target):
dist = {source: 0}
parent = {source: None}
queue = deque([source])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in dist:
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
if target not in dist:
return []
path = []
v = target
while v is not None:
path.append(v)
v = parent[v]
return path[::-1]
JavaScript
function shortestPath(adj, source, target) {
const dist = new Map([[source, 0]]);
const parent = new Map([[source, null]]);
const queue = [source];
for (let head = 0; head < queue.length; head++) {
const u = queue[head];
for (const v of adj[u]) {
if (!dist.has(v)) {
dist.set(v, dist.get(u) + 1);
parent.set(v, u);
queue.push(v);
}
}
}
if (!dist.has(target)) return [];
const path = [];
for (let v = target; v !== null; v = parent.get(v)) path.push(v);
return path.reverse();
}
Cost at a glance
| Time | O(V + E) |
|---|---|
| Space | O(V) |
| Input | Unweighted graph |
| Output | Distances and parent pointers from a source |
Practice problems (7)
Which search finds the fewest stops? Warm-up
A metro map has stations as nodes and one edge per direct connection. Every connection counts as one stop. You want the route with the fewest stops. Pick the method.
Distance labels Warm-up
BFS runs from node 0 on this graph. Neighbors join the queue in increasing number order, and each new node gets its parent's distance plus 1.
Predict which node leaves the queue after node 0, then give the distance node 4 will get.
Shortest path length Standard
Return the number of edges on a shortest path from source to target, or -1 if target cannot be reached. Every edge counts as 1. Directed graphs follow edge direction. In JavaScript, buildAdjacency(graph) returns the adjacency lists.
Reconstruct the path Standard
Return one shortest path from source to target as a list of nodes, starting with source and ending with target. Return [] if target cannot be reached. When several shortest paths exist, any one is accepted. In JavaScript, buildAdjacency(graph) returns the adjacency lists.
Nearest exit in a maze Standard
A maze is a grid where 0 is an open cell and 1 is a wall. You start at entrance, given as [row, col], and each step moves one cell up, down, left or right onto an open cell.
An exit is an open cell on the border of the grid other than the entrance. Return the fewest steps to the nearest exit, or -1 if there is none.
Spot the bug: wrong distances Standard
This function should return the fewest edges from source to target, but it returns a longer distance for some graphs. Click the line with the bug, then fix it.
Word ladder Challenge
A ladder goes from beginWord to endWord by changing one letter at a time. Each word after beginWord must be in wordList.
Return the number of words in the shortest ladder, counting beginWord and endWord. Return 0 if no ladder exists.
Related topics
Next on the path: Dijkstra's algorithm