Sub topic 6
Shortest Paths in Unweighted Graphs
This chapter assumes you have seen the BFS loop from the earlier chapters. You should know that BFS marks vertices as visited when they are enqueued, and that BFS visits the graph in layers. Here we turn the layer idea into an algorithm that computes exact shortest-path distances. We then prove that the algorithm is correct and go through the mistakes that break it.
What "shortest" means here
In an unweighted graph, the length of a path is the number of edges it uses. The distance δ(s, v) from a source s to a vertex v is the smallest number of edges on any path from s to v. If no path exists, δ(s, v) is infinite, and we say v is unreachable.
This definition fits many real problems:
- Fewest moves in a puzzle, where each move counts the same.
- Fewest hops between two routers.
- Degrees of separation in a social network.
- Fewest steps through a maze, where each step costs the same.
When edges carry different costs, "fewest edges" and "cheapest" are no longer the same thing. The section on weighted graphs below shows exactly where BFS breaks.
Computing distances with BFS
The change from plain BFS is small. Plain BFS keeps a visited set. Here we replace it with a dictionary dist that maps each discovered vertex to its distance. A key is present in the dictionary only if the vertex has been visited, so the dictionary also does the visited set's job.
from collections import deque
def bfs_distances(graph, start):
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
queue.append(neighbor)
return dist
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs_distances(graph, 'A')) # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}The algorithm sets a vertex's distance once, when it first discovers that vertex, and never changes it afterwards. A neighbor's distance is always its discoverer's distance plus one.
This trace shows how the queue changes. Note that the distances in the queue never decrease from front to back.
| Step | Dequeued | Newly discovered (distance) | Queue after step |
|---|---|---|---|
| 0 | — | A (0) | A |
| 1 | A | B (1), C (1) | B, C |
| 2 | B | D (2) | C, D |
| 3 | C | E (2) | D, E |
| 4 | D | F (3) | E, F |
| 5 | E | none (F already seen) | F |
| 6 | F | none | empty |
When C is dequeued at step 3, D is skipped because it already has distance 2. This is the key moment. A vertex discovered for the second time cannot have a shorter path waiting for it, because the first discovery already came from the earliest possible layer.
Why the distances are correct
Earlier chapters said that BFS processes vertices in nondecreasing order of distance. We can now prove that the labels it assigns are exact.
Invariant: the queue holds at most two adjacent distance values
At any moment, the queue looks like d, d, …, d, d+1, …, d+1 for some d. This invariant holds at the start, when the queue holds only the source at distance 0. Each step keeps it true. The step dequeues a vertex with label d from the front and appends vertices with label d + 1 at the back. So labels leave the queue in nondecreasing order.
Claim: `dist[v] == δ(s, v)` for every reachable v
The proof has two halves.
- Labels are never too small. Every label
dist[v] = kcomes from a real path of k edges: the chain of discoverers back to s. Sodist[v] ≥ δ(s, v). - Labels are never too large. We use induction on k = δ(s, v). The case k = 0 is the source itself. For k ≥ 1, pick a shortest path to v and let u be the vertex just before v on it, so δ(s, u) = k − 1. By induction,
dist[u] = k − 1, which means u is eventually enqueued and dequeued. When u is dequeued, there are two cases: - v is still undiscovered. Then v gets the label k.
- v was already discovered by some vertex w that was dequeued earlier. Labels leave the queue in nondecreasing order, so
dist[w] ≤ dist[u] = k − 1. That givesdist[v] = dist[w] + 1 ≤ k.
In both cases dist[v] ≤ k.
Together the two halves give equality. Vertices that the algorithm never discovers are exactly the unreachable ones. If v were reachable, the same argument would force BFS to discover it.
Answering a single query: distance from s to t
When you only need one target, you can stop early. Unweighted BFS fixes a vertex's distance the moment it discovers the vertex, so you can return as soon as the target is enqueued. You do not need to wait until it is dequeued.
from collections import deque
def distance(graph, start, goal):
if start == goal:
return 0
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
if neighbor == goal:
return dist[neighbor]
queue.append(neighbor)
return None
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(distance(graph, 'A', 'F')) # 3
print(distance(graph, 'F', 'A')) # None
print(distance(graph, 'A', 'A')) # 0Three edge cases are handled explicitly:
start == goal: the answer is 0. Without the guard, the enqueue-time check would never fire, because the start vertex is already indist. The loop would then run to the end and wrongly returnNone.- Unreachable goal: the queue empties and the function returns
None. Pick one sentinel value (None,-1, orfloat('inf')) and document it. Callers who compare distances with<will get wrong results or aTypeErrorif they receiveNonewithout expecting it. - Direction: in a directed graph, δ(A, F) = 3 but F cannot reach A at all. Distance is not symmetric unless the graph is undirected, which means every edge is stored in both adjacency lists.
Where BFS stops working: weighted edges
BFS minimizes the number of edges, not the total weight. Consider this weighted graph:
| Edge | Weight |
|---|---|
| A → B | 10 |
| A → C | 1 |
| C → B | 1 |
BFS discovers B directly from A and reports a distance of one edge, so the path A → B is "shortest." That path costs 10, while A → C → B costs 2. The argument that "a first discovery comes from the earliest layer" says nothing about cost.
| Edge weights | Algorithm |
|---|---|
| All equal (or none) | BFS, O(V + E) |
| Only 0 and 1 | 0-1 BFS with a deque, O(V + E) |
| Non-negative, arbitrary | Dijkstra's algorithm, O((V + E) log V) with a binary heap |
| Possibly negative | Bellman–Ford, O(VE) |
If every edge has the same positive weight w, BFS still works. Multiply the edge count by w to get the cost.
Common errors
- Using
list.pop(): this removes from the end, which makes the structure a stack and the search depth-first. The distances can come out too large (see the first exercise). - Using
list.pop(0): the result is correct, but each pop shifts the whole list. That costs O(V) per pop and can make the whole search quadratic. Usecollections.deque. - Assigning the distance when dequeuing and not checking for duplicates: a vertex can enter the queue many times. Its first label happens to be correct, but later copies can overwrite it with a larger value if you write
dist[v] = ...without guarding it. - Forgetting reverse edges in an undirected graph: if you add
Btograph['A']but notAtograph['B'], you have built a directed graph. Some distances will then come out infinite or too large. - Reading a missing key as "distance 0": unreachable vertices have no entry in
dist. Adist.get(v, 0)call quietly reports them as the source. Usedist.get(v)and handleNone.
The next chapter extends the same loop so it can return the path itself, not just its length.
Exercise
Run bfs_distances on graph = {'A': ['B', 'C'], 'B': ['E'], 'C': ['D'], 'D': ['E'], 'E': []} from 'A', but replace queue.popleft() with queue.pop(). What distance does E get, and what is the true distance?
Show answer
With pop(), the structure is a stack. A labels B=1 and C=1. C is popped next (it was pushed last) and labels D=2. D is popped and labels E=3. When B is finally popped, E is already labeled, so it stays at 3. The true distance is 2, via A → B → E. The stack broke the guarantee that labels leave the structure in nondecreasing order.
Exercise
For the undirected graph with edges 1–2, 1–3, 2–4, 3–4, 4–5, and 6–7, give the BFS distances from vertex 1. Which vertices are missing from the returned dictionary?
Show answer
The distances are 1: 0, 2: 1, 3: 1, 4: 2, 5: 3. Vertices 6 and 7 are in a different connected component, so BFS never discovers them and they do not appear in the dictionary. Their distance from 1 is infinite.
Exercise
In the proof, why can't a vertex already labeled by some w end up with a label larger than δ(s, v)?
Show answer
Let u be the predecessor of v on a shortest path, with dist[u] = δ(s, v) − 1. The vertex w discovered v before u was processed, so w was dequeued before u. Labels leave a FIFO queue in nondecreasing order, so dist[w] ≤ dist[u]. Therefore dist[v] = dist[w] + 1 ≤ dist[u] + 1 = δ(s, v).