Sub topic 5
Layers, Distances, and the BFS Tree
This chapter assumes you can already write the basic BFS loop with a deque and a visited set, and that you know why vertices are marked visited when they are enqueued. Here we look at the structure BFS leaves behind: each vertex gets a distance, the vertices fall into layers, and the discovery edges together form a tree.
Layers and Distances
Layer k is the set of vertices that BFS discovers at edge distance k from the source. The source alone makes up layer 0. Its unvisited neighbors make up layer 1. The unvisited neighbors of layer 1 make up layer 2, and so on.
To record this, keep a dist dictionary. When a vertex u discovers an unvisited neighbor v, set dist[v] = dist[u] + 1. The dist dictionary can also serve as the visited set, because a vertex has a distance exactly when it has been discovered.
Why the Queue Keeps Layers in Order
BFS processes vertices in order of nondecreasing distance. This follows from an invariant on the queue. At any moment, the queue holds vertices of at most two distances, d and d + 1, and every d vertex sits ahead of every d + 1 vertex.
The invariant holds from the start, when the queue holds only the source at distance 0. Each step keeps it true:
- The front vertex
uhas distance d and is dequeued. - Any neighbor it discovers gets distance d + 1 and joins the back of the queue.
- The back of the queue already held only d or d + 1 vertices, so the order is still nondecreasing.
The queue is first-in, first-out, so layer d is fully drained before any vertex of layer d + 1 is processed.
The BFS Tree
Each vertex other than the source is discovered exactly once, by a single vertex. Record that vertex as the new vertex's parent. The edges parent[v] → v form the BFS tree, which is rooted at the source. A vertex's depth in this tree equals its distance.
from collections import deque
def bfs_layers(graph, start):
dist = {start: 0}
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
parent[neighbor] = node
queue.append(neighbor)
return dist, parent
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
dist, parent = bfs_layers(graph, 'A')
layers = {}
for vertex, d in dist.items():
layers.setdefault(d, []).append(vertex)
print(dist) # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}
print(parent) # {'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D'}
print(layers) # {0: ['A'], 1: ['B', 'C'], 2: ['D', 'E'], 3: ['F']}The edges C→D and E→F belong to the graph but not to the tree. Each one points at a vertex that had already been discovered by the time the edge was examined.
Edges Across Layers
Non-tree edges are limited in where they can go:
| Graph type | Constraint on any edge u → v |
|---|---|
| Undirected | `abs(dist[u] - dist[v]) <= 1` |
| Directed | `dist[v] <= dist[u] + 1` (back edges can drop many layers) |
An edge can never skip forward past the next layer. If u had an edge to an undiscovered v, processing u would put v in layer dist[u] + 1. The next chapter uses this fact to prove that BFS distances are shortest-path distances.
Exercise
In the example graph, add the edge 'B': ['D', 'E'] in place of 'B': ['D']. Which vertex becomes E's parent, and does E's distance change?
Show answer
B is dequeued before C, so B discovers E first and parent['E'] becomes 'B'. The distance stays 2 because B is also in layer 1. The edge C→E becomes a non-tree edge.
Exercise
Can the BFS queue ever hold vertices at distances 2, 3, and 4 at the same time? Explain using the queue invariant.
Show answer
No. A vertex at distance 4 is enqueued only while a distance-3 vertex is being processed. By then every distance-2 vertex has already been dequeued, because the queue is FIFO and ordered by nondecreasing distance. So the queue holds at most two consecutive distances.