AI Wiki中文/EN

Bidirectional search

双向搜索

Search from both endpoints, reverse directed edges correctly, and prove when a meeting gives a shortest path.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Approach 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

Forward discovered: S, A, BBackward discovered: G, C, D
SdF = 0AdF = 1BdF = 1CdB = 1DdB = 1GdB = 0
The next full forward layer from A and B meets at both C and D. The supplied adjacency order chooses C, giving S–A–C–G with three edges. Arrows show original edge directions; backward search follows predecessors.

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 u→vu\to v, forward search can move from uu to vv. Backward search can move from vv to uu because it is reconstructing a possible route into its current vertex. It does not assert that v→uv\to u 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 dF(v)d_F(v) be the minimum number of edges from S to vv, and dB(v)d_B(v) the minimum number from vv to G. BFS in the reverse graph computes the latter. At a discovered common vertex mm, the joined route has length

L(m)=dF(m)+dB(m).L(m)=d_F(m)+d_B(m).

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 rFr_F and rBr_B of their respective ends, and they do not intersect. If a route of length at most rF+rBr_F+r_B 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 rF+1+rBr_F+1+r_B. Integer edge counts leave only one possibility: the shortest length is rF+rB+1r_F+r_B+1. 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:

ExpansionNewly discovered vertices
Forward SA, B
Backward GE, D
Forward AC
Backward EC: 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 O(V+E)O(V+E) time and up to O(V+E)O(V+E) auxiliary space over the supplied graph. The two searches scan each directed adjacency at most once per direction and use O(V)O(V) discovery/path maps. Consequently the whole implementation has O(V+E)O(V+E) worst-case time and auxiliary space. If a reusable predecessor index already exists, the per-query discovery storage is O(V)O(V); that is a different accounting boundary.

The familiar roughly O(bd/2)O(b^{d/2}) intuition assumes comparable branching from both ends and a balanced split of a solution depth dd. 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

  1. 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.
  2. 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.
  3. Does the program’s total auxiliary space equal only its two visited maps? Answer: no. It also constructs reverse adjacency, which can store O(E)O(E) edges, plus frontiers and reconstruction information.
  4. 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?

Choose one answer

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

  1. NetworkX3.6.1 documentation — unweighted bidirectional shortest-path source
    NetworkX developers
  2. Depth-First Iterative-Deepening: An Optimal Admissible Tree Search
    Richard E. Korf · 1985
  3. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.