Sub topic 5
Layers, Distances, and the BFS Tree
The previous chapters built BFS from a queue and a visited set. This chapter looks at the structure BFS produces as it runs. Every vertex it reaches gets a layer number, and the first discovery of each vertex records a parent edge. Together these form the BFS tree. This structure explains why BFS finds shortest paths, which the next chapter proves and uses.
This chapter assumes you can read Python, know the adjacency-list representation from earlier chapters, and have seen the basic BFS loop that marks vertices visited when they are enqueued.
What a Layer Is
A layer is the set of vertices at the same edge distance from the source. Write L0, L1, L2, and so on:
L0holds only the source.L1holds the source's neighbors.Lk+1holds every vertex that has a neighbor inLkand does not already appear in an earlier layer.
BFS finishes all of Lk before it starts Lk+1. That is what the "breadth" in its name means. It goes wide across one distance before going one step deeper.
Recording Distance and Parent
The distance of a vertex is fixed at the moment BFS discovers it, which is when the vertex is enqueued. Its distance is one more than the distance of the vertex that discovered it, and that vertex becomes its parent.
from collections import deque
def bfs_tree(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_tree(graph, 'A')
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'}The dist dictionary also works as the visited set. A vertex counts as visited once it has a distance. You don't need a separate set, and keeping one key set avoids the bug where the two structures drift apart.
Look at vertex D. Both B and C point to it. B is dequeued first, so B discovers D and becomes its parent. When C later looks at D, D already has a distance and nothing changes. A vertex's first discovery is its only discovery.
The BFS Tree
The parent pointers form a tree rooted at the source. Each reached vertex other than the source has exactly one parent, and parents always sit one layer closer to the root, so the pointers cannot form a cycle. This is the BFS tree. Its depth-k level is exactly layer Lk.
Edges of the graph that are not parent edges are called non-tree edges. In the example, C → D and E → F are non-tree edges. Each connects a vertex to something BFS had already discovered.
Why Vertices Come Out in Nondecreasing Distance Order
The key fact is an invariant about the queue's contents. At every moment, the queue holds vertices with distance d at the front, followed by zero or more vertices with distance d + 1 at the back. No other distances appear, and the d + 1 vertices never come before a d vertex.
Here is the argument by induction over queue operations:
- At the start, the queue holds only the source, with distance 0. The invariant holds with
d = 0. - A dequeue removes a front vertex
uwith distanced. The rest of the queue still fits the pattern. If the last distance-dvertex leaves, the queue holds onlyd + 1values, which fits the pattern withd + 1as the new front distance. - While
uis processed, each newly discovered neighbor gets distanced + 1and goes to the back. The back already helddord + 1values, so the pattern survives.
Two consequences follow:
- Vertices leave the queue in nondecreasing distance order. All of layer
kis dequeued before any of layerk + 1. - The queue never holds more than two consecutive layers at once.
The FIFO rule does all the work here. With a stack, step 3 would put d + 1 vertices in front of the remaining d vertices, and the invariant would break at once.
How Far Can an Edge Jump?
The layer structure limits where edges can go. For any edge u → v where u is reachable from the source:
dist[v] <= dist[u] + 1The reason is that when u is processed, v either already has a distance, which is at most dist[u] + 1 by the ordering invariant, or v gets exactly dist[u] + 1 right then.
This rule plays out differently in the two kinds of graph:
| Graph type | Tree edge `u → v` | Non-tree edge `u → v` |
|---|---|---|
| Undirected | `dist[v] = dist[u] + 1` | `dist[v]` is `dist[u]` or `dist[u] + 1` (layers differ by at most 1) |
| Directed | `dist[v] = dist[u] + 1` | `dist[v] <= dist[u] + 1`; it can point back any number of layers |
In an undirected graph, the edge works in both directions, so the rule also gives dist[u] <= dist[v] + 1. Every edge stays inside one layer or links two adjacent layers. A directed edge can point far backward, such as F → A from layer 3 to layer 0, but it can never skip forward over a layer.
You can test this property on any BFS result:
def check_layer_property(graph, dist):
for u in dist:
for v in graph[u]:
if dist[v] > dist[u] + 1:
return False, (u, v)
return True, None
print(check_layer_property(graph, dist)) # (True, None)A failed check means the distances came from a buggy traversal. It is a useful assertion to add when you test BFS variants.
Processing One Layer at a Time
Some problems need the layers themselves, such as "list everyone within two hops" or "how many rounds until the fire spreads everywhere". There are two common ways to get them.
The first way keeps an explicit frontier list for each layer:
def layers(graph, start):
visited = {start}
frontier = [start]
result = []
while frontier:
result.append(frontier)
next_frontier = []
for node in frontier:
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
next_frontier.append(neighbor)
frontier = next_frontier
return result
print(layers(graph, 'A')) # [['A'], ['B', 'C'], ['D', 'E'], ['F']]The second way keeps a single deque and takes a snapshot of its length. By the invariant, the queue holds exactly one full layer at the start of each round:
from collections import deque
def layer_sizes(graph, start):
visited = {start}
queue = deque([start])
sizes = []
while queue:
level_size = len(queue)
sizes.append(level_size)
for _ in range(level_size):
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return sizes
print(layer_sizes(graph, 'A')) # [1, 2, 2, 1]Both versions run in the same time as plain BFS. Choose the frontier-list version when you want the layers as separate lists. Choose the snapshot version when you only need counts or a round number.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Overwriting `dist[v]` every time `v` is seen | Distances grow larger than the true values, and parents change | Assign only when `v` has no distance yet |
| Using a counter that increments on every dequeue as the distance | Distances equal discovery order (0, 1, 2, 3, ...) instead of layer numbers | Compute `dist[node] + 1` from the parent |
| Popping from the right end (`pop()`) | The traversal becomes depth-first, and the layer invariant breaks | Use `popleft()` on a `deque` |
| Marking visited on dequeue but assigning distance on enqueue | Duplicate queue entries, and later entries can overwrite the parent | Mark and assign in the same step, at enqueue time |
| Re-reading the queue length inside a layer loop | Layers merge | Snapshot `len(queue)` first |
Edge Cases
- Unreachable vertices. These never get a key in
distorparent. Code that readsdist[v]for an arbitraryvshould usedist.get(v)or check membership first. - Self-loops. A loop
u → uis a non-tree edge withdist[v] = dist[u], and the membership check ignores it. - Parallel edges. Duplicate entries in an adjacency list are harmless, because the second copy finds the vertex already discovered.
- Ties between parents. When several layer-
kvertices point to the same vertex, the one dequeued first becomes the parent. This depends on adjacency-list order. The distance stays the same, but the tree shape can change.
Exercise
In an undirected graph, BFS from source s gives dist[x] = 2 and dist[y] = 5. Can x and y be joined by an edge? Explain using the layer property.
Show answer
No. In an undirected graph, every edge u–v satisfies |dist[u] − dist[v]| ≤ 1, because the edge can be followed in either direction and each direction gives dist[other] ≤ dist[this] + 1. Here the difference is 3, so no edge can join x and y.
Exercise
Run bfs_tree on the example graph, but change the adjacency list of A to ['C', 'B']. Which parent pointers change, and do any distances change?
Show answer
C is now dequeued before B, so C discovers D first: parent['D'] becomes 'C' instead of 'B'. D is still dequeued before E (D was enqueued first), so parent['F'] stays 'D'. Every distance is unchanged: A 0, B 1, C 1, D 2, E 2, F 3. Neighbor order can change the tree but never the layers.
Exercise
A directed graph has the edge F → A, and BFS from A gives dist['F'] = 3. Does this edge break the rule dist[v] <= dist[u] + 1? Could an edge A → F exist?
Show answer
F → A does not break the rule: dist['A'] = 0 ≤ 3 + 1. Directed non-tree edges may point back any number of layers. An edge A → F cannot exist, because it would force dist['F'] ≤ dist['A'] + 1 = 1, which contradicts dist['F'] = 3.