Bidirectional search
双向搜索
Search from both endpoints, reverse directed edges correctly, and prove when a meeting gives a shortest path.
bidirectional-searchApproach the route from both ends
Suppose a directed map has S→A→C→G and S→B→D→G. Instead of expanding every reachable layer from S alone, start another search at the known goal G. That second search asks which vertices can reach G, then which can reach those vertices.
After one layer from each end, the forward discovered set is S, A, B and the backward set is G, C, D. One more forward layer reaches C and D. Either meeting yields a three-edge route. This is our own small graph; its direction arrows matter.
After exploring one layer from each end
Bidirectional search is a family of algorithms, not a single rule that always halves the work. The version below is bidirectional BFS for unit-cost edges. Korf’s 1985 discussion explains the appeal of searching from both ends when a goal and reverse operations are available; weighted heuristic variants require further rules. Korf, section 5
Backward means predecessors, not outgoing neighbors
For a directed edge , forward search can move from to . Backward search can move from to because it is reconstructing a possible route into its current vertex. It does not assert that is a legal forward action. In the example, G has no outgoing edges but two predecessors. Searching outward from G on the original graph would miss both.
Let be the minimum number of edges from S to , and the minimum number from to G. BFS in the reverse graph computes the latter. At a discovered common vertex , the joined route has length
NetworkX’s implementation makes the directed distinction explicit with successors for one search and predecessors for the other. It also keeps full-layer frontiers and chooses a direction by their sizes. Our code builds its own reverse adjacency and performs a complete layer before selecting a meeting. NetworkX, unweighted shortest-path source, bidirectional helper
Here is why the layer discipline proves optimality. Before a successful expansion, suppose the two discovered sets contain all vertices within radii and of their respective ends, and they do not intersect. If a route of length at most existed, a vertex on that route could lie within both radii, contradicting disjointness. After one more complete forward layer, a meeting constructs a route of length at most . Integer edge counts leave only one possibility: the shortest length is . The backward case is symmetric. This proof requires the discovered-ball invariant; a picture of two touching frontiers is not a substitute.
Join a prefix to a suffix without reversing its meaning
This complete program accepts a finite directed adjacency mapping with repeatable neighbor sequences. Every edge has unit cost; absent entries mean no outgoing edges. The supplied endpoints may represent isolated vertices, so an identical start and goal returns a zero-edge path even without a mapping entry. This differs from libraries that require explicit endpoint membership.
parent points toward S. toward_goal points along original edges toward G, even though it is constructed while searching backward. The meeting vertex is included only once in the returned path. No reserved None marker is used for vertices, so None can itself be an ordinary vertex ID.
def bidirectional_bfs(graph, start, goal):
# Finite, repeatable adjacency sequences; every edge has unit cost.
if start == goal:
return [start]
reverse = {}
for u, neighbors in graph.items():
for v in neighbors:
reverse.setdefault(v, []).append(u)
forward, backward = [start], [goal]
df, db = {start: 0}, {goal: 0}
parent, toward_goal = {start: start}, {goal: goal}
while forward and backward:
go_forward = len(forward) <= len(backward)
frontier = forward if go_forward else backward
adj = graph if go_forward else reverse
own, other = (df, db) if go_forward else (db, df)
links = parent if go_forward else toward_goal
next_layer, meetings = [], []
for u in frontier:
for v in adj.get(u, ()):
if v in own:
continue
own[v] = own[u] + 1
links[v] = u
next_layer.append(v)
if v in other:
meetings.append(v)
if meetings:
middle = min(meetings, key=lambda v: df[v] + db[v])
left = [middle]
while left[-1] != start:
left.append(parent[left[-1]])
path = left[::-1]
u = middle
while u != goal:
u = toward_goal[u]
path.append(u)
return path
if go_forward:
forward = next_layer
else:
backward = next_layer
return None
graph = {'S': ['A', 'B'], 'A': ['C'], 'B': ['D'],
'C': ['G'], 'D': ['G'], 'G': []}
assert bidirectional_bfs(graph, 'S', 'G') == ['S', 'A', 'C', 'G']
assert bidirectional_bfs(graph, 'G', 'S') is None
assert bidirectional_bfs(graph, 'S', 'S') == ['S']
assert bidirectional_bfs({None: [0], 0: ['G']}, None, 'G') == [None, 0, 'G']
assert bidirectional_bfs({'S': [None], None: ['G']}, 'S', 'G') == ['S', None, 'G']
print(bidirectional_bfs(graph, 'S', 'G'))
On equal frontier sizes, the code chooses forward search. It checks every vertex in that chosen layer, then minimizes the joined length among its meetings. The example returns S–A–C–G; S–B–D–G is equally short. A valid shortest path need not be unique.
A first meeting can be premature under another schedule
Consider two routes, S–A–C–E–G of length four and S–B–D–G of length three. Let S’s neighbors be A then B, and G’s reverse neighbors E then D. A tempting implementation alternates one popped vertex from each BFS queue and stops at the first meeting:
| Expansion | Newly discovered vertices |
|---|---|
| Forward S | A, B |
| Backward G | E, D |
| Forward A | C |
| Backward E | C: meeting with joined length 4 |
Both queues individually follow BFS order, yet the algorithm returns four before inspecting the three-edge route through B and D. Its intermediate discovered sets no longer satisfy the complete-layer argument used above. This counterexample concerns that arbitrary vertex-interleaving stopping rule. It does not imply that every optimized early return inside a correctly maintained layer algorithm is wrong.
Unequal costs also break the unweighted proof. A one-edge route costing 20 is not better than a two-edge route costing 2. Bidirectional Dijkstra or heuristic search needs an appropriate lower-bound termination condition, not this BFS meeting rule with weights attached afterward.
For explicit input, our reverse-index construction takes time and up to auxiliary space over the supplied graph. The two searches scan each directed adjacency at most once per direction and use discovery/path maps. Consequently the whole implementation has worst-case time and auxiliary space. If a reusable predecessor index already exists, the per-query discovery storage is ; that is a different accounting boundary.
The familiar roughly intuition assumes comparable branching from both ends and a balanced split of a solution depth . It describes search generation, not the cost of scanning an entire explicit graph to build a reverse index. A huge predecessor fan-in, expensive inverse operations or strongly unequal frontiers can remove the advantage. Choosing the smaller frontier counts vertices, not their outgoing work, and does not guarantee a meeting at the exact midpoint. A chain with tied singleton frontiers can be explored entirely forward by our tie rule.
Check direction, stopping and storage
- G has no outgoing edges. Does that prevent backward search from G? Answer: no. Backward search needs incoming predecessors; in the example these are C and D.
- Why does alternating one vertex at a time fail in the four-versus-three example? Answer: the first shared vertex is found before the shallower competing connection has been examined. The complete discovered-ball invariant is missing.
- Does the program’s total auxiliary space equal only its two visited maps? Answer: no. It also constructs reverse adjacency, which can store edges, plus frontiers and reconstruction information.
- Does choosing the smaller frontier guarantee exactly half the solution depth from each end? Answer: no. Branching and tie rules affect the split; even a singleton chain can be searched only forward.
Separate a midpoint theorem from a speed claim
The 2016 MM paper gives “meeting in the middle” a precise meaning: neither direction expands past half the optimal solution cost under its algorithmic conditions. That is stronger than merely finding a common vertex. The authors also explicitly avoid claiming that MM is always the fastest or expands the fewest nodes among all bidirectional methods. This article uses their introductory definition and scope, not a reproduction of the full MM algorithm. Holte and colleagues, abstract and introduction
To evaluate a practical implementation, measure predecessor-index construction separately from query time, then compare repeated queries with a reused index. Record edges scanned as well as vertices discovered. For a correctness baseline, compare every returned path’s edge count with BFS on the same directed graph. For a different way to limit the stored frontier, continue with IDA*, which trades repeated work for depth-first search storage instead of adding a second search direction.
Make a prediction, then check
In a directed graph G has no outgoing edges.What should backward search inspect?
Learning objectives
- Search predecessors in directed graphs and prove the first successful layer’s shortest length using complete discovered balls.
- Explain the premature vertex-interleaving counterexample and separately account for reverse indexing,query work and frontier storage.
Prerequisites & connections
Explore related knowledge →References
- NetworkX3.6.1 documentation — unweighted bidirectional shortest-path source
NetworkX developers - Depth-First Iterative-Deepening: An Optimal Admissible Tree Search
Richard E. Korf · 1985 - Bidirectional Search That Is Guaranteed to Meet in the Middle
Robert C. Holte; Ariel Felner; Guni Sharon; Nathan R. Sturtevant · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check:source locations,independent shortest-distance comparison,executed counterexamples and full bilingual rereading;no independent human peer review.
- Reread bilingual shortest-length proof,direction and reconstruction;verified premature4-edge meeting versus3-edge optimum and O(E) reverse-index storage.
- Seven new checks executed successfully:4096 four-vertex directed graphs,729 three-vertex weighted graphs,40 random six-vertex graphs,thresholds and invalid heuristics,predecessor illustration,premature-meeting counterexample and boundaries.Search suite totals12 checks;95 article programs executed.
Source locations checked:
- NetworkX3.6.1 documentation — unweighted bidirectional shortest-path source · Live source page lines254–367:directed G.pred/G.succ,whole-layer fringe selection,predecessor/successor reconstruction and endpoint membership exceptions. Own code deliberately finishes a layer,builds reverse adjacency,and permits implicit isolated endpoints/None IDs.
- Depth-First Iterative-Deepening: An Optimal Admissible Tree Search · Read original102–103,section5:explicit goal,inverse operations and balancing time/space discussion. Article separates ideal balanced generation from explicit reverse-index construction.
- Bidirectional Search That Is Guaranteed to Meet in the Middle · Read PDF1 abstract and introduction:midpoint means no expansion beyond C*/2 under MM conditions;authors explicitly do not claim globally fewest nodes or fastest runtime. No whole-algorithm proof claimed.
Related topics