Sub topic 6
Shortest Paths in Unweighted Graphs
This chapter assumes you know how BFS uses a FIFO queue, why vertices are marked visited when they are enqueued, and how BFS explores a graph in layers. It turns those layers into a practical result: the fewest-edges distance from a source to every reachable vertex.
What "shortest" means here
In an unweighted graph, every edge counts as 1. The length of a path is its number of edges. The shortest-path distance from s to v is the smallest number of edges on any path from s to v. If no path exists, the distance is undefined, or infinite.
BFS computes these distances directly. When a vertex u discovers a new neighbor v, set dist[v] = dist[u] + 1.
Computing distances
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 dist dictionary also works as the visited set. A vertex is in dist exactly when it has been discovered. Vertices that are missing from the result are unreachable from start.
D can be reached through B or through C. Both routes have two edges. BFS keeps whichever discovery happens first, and both give the same distance.
Why the first discovery is the shortest
The argument has two halves:
- No label is too small. Each
dist[v]comes from following a real path: the path tou, plus the edgeu → v. Sodist[v]is never less than the true distance. - No label is too large. The queue always holds vertices in nondecreasing order of
dist, with at most two consecutive values present at once. Take a vertexvwhose true distance isk, and letube its predecessor on some shortest path, souhas true distancek - 1. By induction,ureceives the labelk - 1. Whenuis dequeued, eithervgets the labelk, orvwas already discovered from a vertex dequeued earlier. Any such vertex has a label of at mostk - 1, sov's label is at mostk.
Together, the two halves give dist[v] = true distance.
Common errors
| Mistake | Effect |
|---|---|
| Marking visited on dequeue, not enqueue | A vertex can be enqueued many times, which wastes work; overwriting `dist` on a later dequeue can store a wrong value |
| Using a stack (`pop()`) instead of `popleft()` | The search becomes depth-first, and distances are no longer shortest |
| Updating `dist` when a vertex is seen again | Labels already set can get overwritten with larger values |
| Running BFS on weighted edges | The result minimizes edge count, not total weight |
Exercise
Given graph = {1: [2, 3], 2: [4], 3: [4], 4: [5], 5: [], 6: [5]}, what does bfs_distances(graph, 1) return, and what does the result say about vertex 6?
Show answer
{1: 0, 2: 1, 3: 1, 4: 2, 5: 3}. Vertex 6 does not appear, so it cannot be reached from 1. The edge 6 → 5 points into the reachable part of the graph, but no edge leads out of it to 6.
Exercise
In bfs_distances, why is it safe never to update dist[neighbor] once it is set?
Show answer
The queue processes vertices in nondecreasing order of distance. The first vertex to discover a neighbor therefore has the smallest possible distance among all vertices that can reach it, so the first label is already the shortest. Any later discovery would give an equal or larger value.