Sub topic 14
Bidirectional BFS
This chapter assumes you already know standard BFS with a queue and a visited set, path reconstruction from parent pointers, and the O(V + E) analysis from earlier chapters. Bidirectional BFS answers a narrower question: what is the shortest path from one known start to one known goal? It answers it by running two searches at once, one forward from the start and one backward from the goal, and stopping when they meet.
Why two searches beat one
Suppose each vertex has about b neighbors and the goal is d edges away. A single BFS explores roughly b^d vertices before it reaches the goal. Two searches that each go d/2 deep explore about 2 · b^(d/2) vertices in total.
| Branching b | Depth d | One-sided BFS | Bidirectional BFS |
|---|---|---|---|
| 10 | 6 | about 1,000,000 | about 2,000 |
| 3 | 10 | about 59,000 | about 486 |
The worst-case bound is still O(V + E). The gain comes from graphs that branch quickly, such as social networks, word ladders, and puzzle state spaces.
The algorithm
- Keep a parent map and a frontier queue for each side.
- Pick the side with the smaller frontier and expand one whole layer of it.
- When a newly discovered neighbor already appears in the other side's parent map, the searches have met. Join the two half-paths there.
- If either frontier empties first, no path exists.
from collections import deque
def expand_layer(graph, frontier, parent_this, parent_other):
for _ in range(len(frontier)):
node = frontier.popleft()
for neighbor in graph[node]:
if neighbor in parent_other:
parent_this[neighbor] = node
return neighbor
if neighbor not in parent_this:
parent_this[neighbor] = node
frontier.append(neighbor)
return None
def build_path(meet, parent_s, parent_g):
path = []
node = meet
while node is not None:
path.append(node)
node = parent_s[node]
path.reverse()
node = parent_g[meet]
while node is not None:
path.append(node)
node = parent_g[node]
return path
def bidirectional_bfs(graph, start, goal):
if start == goal:
return [start]
parent_s, parent_g = {start: None}, {goal: None}
frontier_s, frontier_g = deque([start]), deque([goal])
while frontier_s and frontier_g:
if len(frontier_s) <= len(frontier_g):
meet = expand_layer(graph, frontier_s, parent_s, parent_g)
else:
meet = expand_layer(graph, frontier_g, parent_g, parent_s)
if meet is not None:
return build_path(meet, parent_s, parent_g)
return None
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D', 'E'],
'D': ['B', 'C', 'F'],
'E': ['C', 'F'],
'F': ['D', 'E'],
}
print(bidirectional_bfs(graph, 'A', 'F')) # ['A', 'B', 'D', 'F']Why the first meeting is shortest
The code checks each new vertex against the other side as soon as it is discovered, so the two visited sets never overlap until the meeting. Suppose a shorter path existed while the forward side is expanding depth ds and the backward side has reached depth db. Then some vertex on that path would lie within ds of the start and within db of the goal. That vertex would already be in both maps, which contradicts the no-overlap invariant. So the first meeting gives length ds + 1 + db, and nothing shorter exists.
Common errors
- Checking for a meeting only when a vertex is dequeued, not when it is discovered. This breaks the invariant and can overshoot.
- Always expanding the same side. Choosing the smaller frontier keeps both sides balanced, and balance is where the speedup comes from.
- Using it for one-to-all distances. Bidirectional BFS needs a single known goal. For distances to every vertex, use plain BFS.
- Expecting it to save memory in the worst case. Both parent maps can still grow to O(V).
Exercise
In a graph where every vertex has 4 neighbors and the goal is 8 edges from the start, roughly how many vertices do one-sided BFS and bidirectional BFS each explore?
Show answer
One-sided BFS explores about 4^8 = 65,536 vertices. Bidirectional BFS explores about 2 · 4^4 = 512 vertices, since each side only goes 4 layers deep.
Exercise
You run bidirectional_bfs on a directed graph without changing the adjacency list. What goes wrong?
Show answer
The backward search follows edges out of the goal instead of into it. It can report a "path" that uses edges in the wrong direction, or miss real paths. The goal side needs a reversed adjacency list.