Sub topic 2
Layers, Distances, and the BFS Tree
This chapter assumes you know Python dictionaries and sets, collections.deque, Big-O notation, and the basic BFS loop from the previous chapter.
Layers and the BFS Tree
BFS removes vertices from the queue in layers. Layer 0 holds only the source. Layer k + 1 holds the unvisited neighbors of vertices in layer k. The queue is FIFO, so every vertex in layer k comes out before any vertex in layer k + 1. The first time BFS discovers a vertex, the edge it used to get there is a tree edge. Together, the tree edges form the BFS tree.
Shortest Paths in Unweighted Graphs
A vertex's layer number equals the fewest edges on any path from the source to it. Here is why. Suppose vertex v is at distance d. Then v has a neighbor u at distance d − 1. By induction, u is in layer d − 1, so BFS discovers v no later than layer d. BFS also can't reach v earlier, because that would mean a shorter path exists. This argument only holds when every edge costs the same. With unequal weights, use Dijkstra's algorithm or, for weights of 0 and 1, the 0-1 BFS covered later.
Reconstructing Paths with Parent Pointers
When BFS discovers a neighbor, record the vertex it came from. The parent dictionary then does two jobs: it serves as the visited set, and it stores the BFS tree. To get the path, follow parent pointers back from the goal, then reverse the list.
from collections import deque
def shortest_path(graph, start, goal):
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
queue.append(neighbor)
return None
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(shortest_path(graph, 'A', 'F')) # ['A', 'B', 'D', 'F']Why BFS Runs in O(V + E) Time
Each vertex enters and leaves the queue at most once, which costs O(V) in total. Each vertex's adjacency list is scanned once, when that vertex is dequeued. In a directed graph this covers E edges in total, and in an undirected graph it covers 2E. The total time is O(V + E). The queue and the parent dictionary each hold at most V entries, so extra space is O(V).
| Representation | BFS time |
|---|---|
| Adjacency list | O(V + E) |
| Adjacency matrix | O(V²) |
Exercise
In the example graph, which vertex is E's parent, and why does F get D as its parent instead of E?
Show answer
E's parent is C. D and E are both in layer 2, but D was enqueued first because B is dequeued before C. So D is dequeued first and discovers F, and when E is processed later, F is already in parent.