Sub topic 14
Bidirectional BFS
This chapter assumes you already know how plain BFS finds shortest paths in unweighted graphs, how parent pointers rebuild a path, and why BFS runs in O(V + E) time. Bidirectional BFS runs the same layer-by-layer search from both ends and stops when the two searches meet. It produces the same answer as ordinary BFS. On large graphs it usually touches far fewer vertices.
The idea: two small searches beat one big one
Ordinary BFS from start grows a ball of explored vertices outward until the ball contains goal. If the shortest path has length d, the ball reaches radius d. Bidirectional BFS grows two balls, one from start and one from goal. Each needs to reach only about d/2 before they touch.
The payoff depends on how fast the frontier grows. Suppose every vertex has about b neighbors. This number is called the branching factor. A search to depth d then touches roughly b^d vertices, while two searches to depth d/2 touch roughly 2·b^(d/2).
| Branching factor b | Path length d | One-sided BFS (≈ sum of b^k, k ≤ d) | Bidirectional (≈ 2 × sum of b^k, k ≤ d/2) |
|---|---|---|---|
| 10 | 6 | 1,111,111 | 2,222 |
| 3 | 10 | 88,573 | 728 |
| 2 | 20 | 2,097,151 | 4,094 |
These numbers assume a tree-like graph with no repeated vertices. Real graphs have cycles and overlap, so the gains are smaller in practice. They are still often several orders of magnitude on social networks, word ladders, and puzzle state spaces.
The algorithm
The search keeps two parent maps, parent_fwd and parent_bwd. Each one is the visited set for its side and also its BFS tree. A round does the following:
- Pick the side whose frontier is smaller.
- Expand exactly one layer of that side. Dequeue every vertex that was in the frontier when the round began.
- When you discover a new neighbor, record its parent. Then check whether the other side has already seen it. If it has, that vertex is the meeting point.
- Rebuild the path. Walk
parent_fwdfrom the meeting vertex back tostartand reverse that half. Then walkparent_bwdfrom the meeting vertex forward togoal.
The backward search has to follow edges in reverse. In an undirected graph the reverse graph is the same graph. In a directed graph you must build it.
from collections import deque
def reverse_edges(graph):
rev = {node: [] for node in graph}
for u, neighbors in graph.items():
for v in neighbors:
rev[v].append(u)
return rev
def expand_layer(graph, frontier, parent_this, parent_other):
"""Expand one full layer. Return a meeting vertex, or None."""
for _ in range(len(frontier)):
node = frontier.popleft()
for neighbor in graph[node]:
if neighbor not in parent_this:
parent_this[neighbor] = node
if neighbor in parent_other:
return neighbor
frontier.append(neighbor)
return None
def join_paths(meet, parent_fwd, parent_bwd):
path = []
node = meet
while node is not None:
path.append(node)
node = parent_fwd[node]
path.reverse()
node = parent_bwd[meet]
while node is not None:
path.append(node)
node = parent_bwd[node]
return path
def bidirectional_shortest_path(graph, start, goal, reverse_graph=None):
if reverse_graph is None:
reverse_graph = graph # correct only for undirected graphs
if start == goal:
return [start]
parent_fwd = {start: None}
parent_bwd = {goal: None}
frontier_fwd = deque([start])
frontier_bwd = deque([goal])
while frontier_fwd and frontier_bwd:
if len(frontier_fwd) <= len(frontier_bwd):
meet = expand_layer(graph, frontier_fwd, parent_fwd, parent_bwd)
else:
meet = expand_layer(reverse_graph, frontier_bwd, parent_bwd, parent_fwd)
if meet is not None:
return join_paths(meet, parent_fwd, parent_bwd)
return None
undirected = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D', 'E'],
'D': ['B', 'C', 'F'],
'E': ['C', 'F'],
'F': ['D', 'E'],
}
print(bidirectional_shortest_path(undirected, 'A', 'F')) # ['A', 'B', 'D', 'F']
directed = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bidirectional_shortest_path(directed, 'A', 'F',
reverse_edges(directed))) # ['A', 'B', 'D', 'F']
split = {'A': ['B'], 'B': ['A'], 'C': []}
print(bidirectional_shortest_path(split, 'A', 'C')) # NoneHere is the trace for the undirected example. The forward side expands A and discovers B and C. The backward frontier [F] is now smaller, so it expands and discovers D and E. The frontiers are tied at two vertices each, so the forward side expands next. From B it discovers D, which parent_bwd already contains. D is the meeting vertex. The forward half is A, B, D and the backward half adds F.
Why the first meeting gives a shortest path
This is the most important correctness point. Suppose the forward side has fully explored distances up to a and the backward side up to b, and they have not met yet. Then the shortest path length D is at least a + b + 1. If D were at most a + b, the vertex at position a on a shortest path would be within a of start and within D − a ≤ b of goal. Both sides would already contain it, and the meeting would have been detected when the second side discovered it.
Now the forward side expands layer a and finds a neighbor v that the backward side knows at backward distance at most b. The joined path has length a + 1 + distbwd(v), which can't be smaller than D ≥ a + b + 1. So distbwd(v) = b and the path has length exactly D. The first meeting is optimal, so returning at once is safe.
That argument depends on each side being "complete up to some depth." Two implementation choices keep that true:
- Expand whole layers. The
for _ in range(len(frontier))loop processes only vertices present when the round began. - Check the other side's full parent map, not only its current frontier. Vertices found in earlier layers count too.
Failure modes and gotchas
Alternating one vertex at a time
If you pop one vertex from each side in turn, a frontier can mix depth a and depth a + 1. The completeness argument breaks, and the first meeting can produce a path one edge longer than optimal. Some meetings will still be correct, so the bug tends to show up only on certain graphs.
Forgetting to reverse a directed graph
Searching backward along the original edges finds paths from goal to vertices, not from vertices to goal. The function will return something path-shaped that uses edges in the wrong direction. Build the reverse adjacency list once, in O(V + E), before you search.
Checking membership in the wrong map
A common typo is testing neighbor in parent_this where you meant parent_other. The meeting is then never detected, and the search degrades into two full BFS runs that both end with None.
Expanding the larger side
Always expanding forward, or alternating strictly, still gives correct results. It can lose most of the speedup, though. If start is a hub with 10,000 neighbors and goal is a leaf, you want the goal side to do most of the work. Choosing the smaller frontier is a cheap heuristic that works well in practice.
Carrying the idea over to weighted graphs
Bidirectional Dijkstra exists, but its first meeting is not guaranteed to be optimal. It needs a separate stopping test that compares the sum of the two queue minimums against the best path found so far. The simple rule above is valid only for unweighted, layer-by-layer BFS.
When to use it
Bidirectional BFS needs a single goal vertex that you know in advance, and it needs to be able to step backward from that goal. Several common BFS tasks fail one of those requirements.
| Situation | Bidirectional BFS? | Reason |
|---|---|---|
| One start, one known goal, large branching factor | Yes | This case gets the full b^d to 2·b^(d/2) gain |
| Word ladder, sliding puzzle with a known solved state | Yes | Both ends are explicit, and moves can be reversed |
| Goal defined by a predicate ("any exit cell") | No | There is no single vertex to search back from |
| Distances from one source to all vertices | No | Plain BFS already has to visit everything |
| Directed graph without a cheap reverse | Usually no | Building the reverse graph may cost more than you save |
| Small graph or short paths | Rarely | The extra bookkeeping outweighs the savings |
For many sources or many goals, multi-source BFS from an earlier chapter is usually the right tool.
Exercise
A graph has branching factor about 4 and the shortest path from start to goal has length 8. Roughly how many vertices does one-sided BFS touch compared with bidirectional BFS, using the tree-like estimate?
Show answer
One-sided BFS touches about 1 + 4 + 16 + ... + 4^8 = (4^9 − 1)/3 = 87,381 vertices. Bidirectional BFS runs two searches to depth 4, each touching about 1 + 4 + 16 + 64 + 256 = 341 vertices, so about 682 in total. That is roughly 128 times fewer.
Exercise
A colleague changes expand_layer to pop a single vertex per call instead of a whole layer, and alternates sides on every call. Why can this return a path that is not shortest?
Show answer
After single-vertex steps, a frontier can hold vertices at two different depths. The proof that the first meeting is optimal assumes each side has fully explored every distance up to its current depth. Without that, a meeting can occur through a vertex that is one layer deeper than necessary on one side, giving a path one edge longer than the true shortest path.
Exercise
You call bidirectionalshortestpath(directed, 'A', 'F') on the directed example without passing reverse_edges(directed). What goes wrong?
Show answer
The backward search follows F's outgoing edges, and F has none, so the backward frontier empties after one expansion and the loop returns None even though A → B → D → F exists. On other directed graphs the bug can instead return a path that traverses edges in the wrong direction.