Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Implicit Graphs & BFS Variants

Grids and state spaces; multi-source, 0-1 and bidirectional BFS.

The 8-puzzle has 181,440 reachable positions and Rubik's cube about 4.3×10194.3 \times 10^{19}, yet both are just graphs: positions joined by moves. Nobody stores them. A search generates each vertex's neighbors when it needs them, and the hard questions move elsewhere: what exactly is a state, how many states are there, and which variant of BFS reaches the goal before time or memory runs out?

What you’ll learn

  • Model a problem as an implicit graph: choose a state that records everything the future depends on, count the states, and generate neighbors on the fly.
  • Prove multi-source BFS and 0-1 BFS correct, run both in O(n+m)O(n + m), and use Dial's buckets for small integer weights.
  • Implement bidirectional BFS with a correct stopping rule, and explain when meeting in the middle saves an exponential factor and when only a constant one.
  • Explain why memory limits large searches, how frontier and disk-based search cope, and what is known about reachability in small space.

States, moves and how many there are

ProblemStateNumber of statesMoves per state
A combination lock with 4 wheelsthe four digits10410^48: turn one wheel up or down
The 8-puzzlethe arrangement of the tiles9!/2=181,4409!/2 = 181{,}440 reachable2 to 4
A grid maze with kk keys and locked doors(cell, set of keys held)RC⋅2kR C \cdot 2^k4
Word laddera dictionary wordthe dictionary size NNup to 25L25L candidates for words of length LL
Rubik's cubethe position and orientation of every piece≈4.3×1019\approx 4.3 \times 10^{19}18 face turns
A BFS over all 181,440 positions of the 8-puzzle runs in under a second even in Python and shows that the hardest positions need 31 moves (two positions are that far from the solved one with the blank in a corner). For Rubik's cube, a computation of about 35 CPU-years on Google's machines established in 2010 that every position can be solved in at most 20 face turns, counting a half turn as one.

The costs follow from the counts. BFS on an implicit graph takes O(S⋅b)O(S \cdot b) time for SS reachable states with at most bb moves each, plus the cost of encoding and hashing states, and O(S)O(S) memory for the visited set, which is usually what runs out first.

Predict before you look

A 50×5050 \times 50 grid maze has six keys, labeled a to f, and doors that need them. Counting every combination of a cell and a set of keys held, how many states may BFS have to visit?

Show the answer

160000 states

50⋅50=2,50050 \cdot 50 = 2{,}500 cells times 26=642^6 = 64 sets of keys: 160,000160{,}000 states, each with 4 moves, so BFS examines at most about 6.4×1056.4 \times 10^5 moves. With twenty keys it would be 2,500⋅220≈2.6×1092{,}500 \cdot 2^{20} \approx 2.6 \times 10^9 states: the exponent hidden in the state, not the size of the grid, decides what is feasible.

Many sources, and edges of weight 0 or 1

When edges weigh 0 or 1, as in "moving along an arrow is free and against it costs 1" or "walking is free and each wall broken costs 1", BFS's queue is no longer enough, and Dijkstra's heap is more than needed. 0-1 BFS keeps a deque: a vertex reached by a 0-edge goes to the front, one reached by a 1-edge to the back.

python
from collections import deque

def zero_one_bfs(adj, s):
    """adj[u] = list of (v, w) with w in {0, 1}. Distances from s (None = unreachable)."""
    dist = [None] * len(adj)
    dist[s] = 0
    dq = deque([s])
    done = [False] * len(adj)
    while dq:
        u = dq.popleft()
        if done[u]:
            continue                        # a stale copy: u was finalized earlier
        done[u] = True
        for v, w in adj[u]:
            if dist[v] is None or dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                if w == 0:
                    dq.appendleft(v)        # same distance as u: front
                else:
                    dq.append(v)            # one more: back
    return dist

Each edge is relaxed once, when its tail is first popped, so the deque receives at most m+1m + 1 entries: O(n+m)O(n + m) time. A vertex can enter the deque twice when a cheaper route turns up later, and the done test skips the stale copy. Tested against Dijkstra's algorithm on thousands of random graphs.

DerivationWhy the deque works
  1. deque=D,…,D⏟front, D+1,…,D+1⏟back\text{deque} = \underbrace{D, \dots, D}_{\text{front}},\ \underbrace{D + 1, \dots, D + 1}_{\text{back}}

    Invariant. Record with each entry the distance it was pushed with (its key). At every moment the keys in the deque, from front to back, are nondecreasing and take at most two values, DD and D+1D + 1, where DD is the front key:

  2. push front: D≤D≤⋯push back: ⋯≤D+1≤D+1\text{push front: } D \le D \le \cdots \qquad\qquad \text{push back: } \cdots \le D + 1 \le D + 1

    Each step keeps it. Popping the front leaves keys in {D,D+1}\{D, D + 1\}. A popped vertex uu with key DD pushes key DD at the front along 0-edges and key D+1D + 1 at the back along 1-edges. When the last key DD leaves, the front key becomes D+1D + 1 and the allowed pair moves up to {D+1,D+2}\{D + 1, D + 2\}:

  3. u popped for the first time with key D⟹dist[u]=δ(s,u)=Du \text{ popped for the first time with key } D \quad\Longrightarrow\quad \text{dist}[u] = \delta(s, u) = D

    So the front holds a minimum, just as the top of Dijkstra's heap does, and Dijkstra's argument applies unchanged: weights are non-negative, so no route through the vertices still waiting can undercut the front. The first time a vertex is popped, its distance is final:

For integer weights from 0 to CC, Dial's algorithm (1969) generalizes the deque to buckets indexed by distance. Settle the vertices bucket by bucket; an edge leads at most CC buckets ahead, so a circular array of C+1C + 1 buckets suffices, and since no distance exceeds (n−1)C(n - 1)C the time is O(m+nC)O(m + nC). It beats a binary heap when CC is small; 0-1 BFS is the case C=1C = 1.

Meeting in the middle: bidirectional BFS

Bidirectional search (Pohl, 1971) runs one BFS forward from ss and one backward from tt, along reversed edges, and stops when they meet. If every state has bb successors and tt is dd moves away, one search explores about bdb^d states, while two searches that meet halfway explore about 2bd/22b^{d/2}: with b=10b = 10 and d=8d = 8, roughly 2×1042 \times 10^4 states instead of 10810^8. The backward search needs predecessors, which is easy when moves are reversible (puzzles, word ladders) and impossible when the goal is given only by a test.

DerivationProof
  1. no common vertex yet⟹δ(s,t) ≥ i+j+1\text{no common vertex yet} \quad\Longrightarrow\quad \delta(s, t) \ \ge\ i + j + 1

    No meeting so far means tt is far. If L=δ(s,t)≤i+jL = \delta(s, t) \le i + j, take a shortest path and its vertex xx at distance min⁡(i,L)\min(i, L) from ss. The forward search has reached xx, and xx is within L−min⁡(i,L)≤jL - \min(i, L) \le j of tt, so the backward search has reached it too: a common vertex. Hence

  2. i+j+1 ≤ δ(s,t) ≤ δ(s,v)+δ(v,t) ≤ i+1+ji + j + 1 \ \le\ \delta(s, t) \ \le\ \delta(s, v) + \delta(v, t) \ \le\ i + 1 + j

    The meeting vertex closes the gap. vv has δ(s,v)=i+1\delta(s, v) = i + 1 and backward distance at most jj, so

  3. Equality holds throughout (in particular δ(v,t)=j\delta(v, t) = j), so every meeting vertex found while expanding this layer gives the same, optimal length, and the first one will do.

python
def bidirectional_bfs(adj, radj, s, t):
    """Fewest edges from s to t (-1 if unreachable); radj holds the reversed edges."""
    if s == t:
        return 0
    dist = [{s: 0}, {t: 0}]                      # forward and backward distances
    frontier = [[s], [t]]
    graphs = [adj, radj]
    while frontier[0] and frontier[1]:
        side = 0 if len(frontier[0]) <= len(frontier[1]) else 1   # grow the smaller side
        mine, other = dist[side], dist[1 - side]
        nxt = []
        for u in frontier[side]:                 # one whole layer
            for v in graphs[side][u]:
                if v not in mine:
                    mine[v] = mine[u] + 1
                    if v in other:
                        return mine[v] + other[v]
                    nxt.append(v)
        frontier[side] = nxt
    return -1

Expanding the smaller frontier keeps the two searches balanced even when one direction branches more. Checked against plain BFS on 30,000 random directed and undirected graphs. The dictionaries make it work for any hashable states.

How much the meeting saves depends on how fast the number of states grows with distance. In a tree-like space it grows like bdb^d and the saving is exponential. On an open grid the cells within distance rr number only 2r2+2r+12r^2 + 2r + 1, so the layers grow linearly and halving the radius saves much less. The same meet-in-the-middle idea solves subset sum in O(2n/2)O(2^{n/2}) instead of O(2n)O(2^n): see the lesson Meet in the Middle.

Predict before you look

On an open grid, tt is 100 steps from ss. One BFS explores every cell within distance 100 of ss; bidirectional BFS explores the cells within distance 50 of ss and within distance 50 of tt. Roughly what percentage of the one-directional work is that?

Show the answer

50 %

One search covers 2⋅1002+2⋅100+1=20,2012 \cdot 100^2 + 2 \cdot 100 + 1 = 20{,}201 cells, and two searches of radius 50 cover 2×5,101=10,2022 \times 5{,}101 = 10{,}202: about 50%. Area grows quadratically, so halving the radius quarters each search, and there are two of them. In a tree with branching factor 10, the same split would cut about 1010010^{100} states to about 2×10502 \times 10^{50}.

When memory is the limit

BFS must remember every state it has seen, and in large puzzles that, not time, is the wall. Two observations push it back.

Keeping only the frontier layers is the idea of frontier search; storing the layers on disk, sorted so that duplicates disappear in one streaming pass, is the idea of disk-based BFS. With both, and many processors, Korf and Schultze (2005) completed the first full breadth-first search of the 15-puzzle, more than 101310^{13} states; its hardest positions need 80 moves. Layers can also be bit vectors over ranked states, and when a dense graph is stored as adjacency bitsets, a frontier vertex's new neighbors are one AND-NOT of two bitsets: BFS in O(n2/w)O(n^2 / w) word operations on ww-bit words (see Bit-Parallel Algorithms).

How little memory can reachability use at all? BFS needs Θ(n)\Theta(n) bits. Savitch (1970) decides whether tt is reachable from ss in a directed graph with O(log⁡2n)O(\log^2 n) bits, by recursing on "is there a path of length at most 2k2^k through some middle vertex?", but in nO(log⁡n)n^{O(\log n)} time. For undirected graphs Reingold (2005) needs only O(log⁡n)O(\log n) bits, which also means polynomial time. For directed graphs, the best known polynomial-time algorithm still uses n/2Θ(log⁡n)n / 2^{\Theta(\sqrt{\log n})} bits (Barnes, Buss, Ruzzo & Schieber, 1998), barely below nn.

Key takeaways

  • An implicit graph is a state space generated on demand. A correct state records everything the future depends on (cell plus keys, walls broken, or time), and the number of states sets the cost.
  • Multi-source BFS is BFS from a virtual super-source. 0-1 BFS keeps a deque whose keys span two consecutive values, so both run in O(n+m)O(n + m); Dial's buckets extend this to integer weights up to CC in O(m+nC)O(m + nC).
  • Bidirectional BFS that expands whole layers may stop at the first meeting, with δ(s,t)=i+1+j\delta(s, t) = i + 1 + j. It turns bdb^d into about 2bd/22b^{d/2} in tree-like spaces but saves only a constant factor on grids.
  • Memory, not time, limits large searches: undirected BFS needs only three layers at a time, and disks and bitsets stretch it past 101310^{13} states. Undirected connectivity fits in O(log⁡n)O(\log n) space (Reingold), while directed reachability in small space remains open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A 0-1 BFS marks each vertex as finished the first time it is pushed, as plain BFS does. On the edges s→vs \to v of weight 1, s→as \to a of weight 0 and a→va \to v of weight 0, what distance does it report for vv?

  1. 0, the true distance
  2. 1
  3. 2
  4. It never reaches vv
Show the answer

B. 1

Popping ss pushes vv to the back with distance 1 and aa to the front with distance 0. Popping aa finds the free edge to vv, but vv is already marked, so the cheaper route is ignored and vv keeps 1 instead of 0. In 0-1 BFS, as in Dijkstra's algorithm, a vertex is final only when it is popped.

Question 2

"Fewest steps from S to E in a grid, where you may break through at most kk walls." Which BFS state is correct?

  1. The cell alone
  2. (cell, direction of the last move)
  3. (cell, number of walls broken so far)
  4. (cell, number of steps taken so far)
Show the answer

C. (cell, number of walls broken so far)

What remains possible depends on how many breaks are left, so arrivals at one cell with different counts are different states: RC(k+1)RC(k + 1) of them. BFS over these states finds the fewest steps.

Question 3

In layer-by-layer bidirectional BFS, the forward search has completed layers 0 to 3 and the backward search layers 0 to 2, with no common vertex. Expanding forward layer 3 then discovers a vertex that the backward search has reached. What is δ(s,t)\delta(s, t)?

  1. At most 6, so the search must continue to be sure
  2. Exactly 5
  3. Either 6 or 7
  4. Exactly 6
Show the answer

D. Exactly 6

No common vertex after those layers means δ(s,t)≥3+2+1=6\delta(s, t) \ge 3 + 2 + 1 = 6, and the meeting vertex lies on a path of length 4+2=64 + 2 = 6. So δ(s,t)=6\delta(s, t) = 6, and the search can stop at once.

Question 4

BFS keeps Θ(n)\Theta(n) bits for its visited set. Which statement about reachability in less memory is true?

  1. Undirected ss–tt connectivity can be decided deterministically in O(log⁡n)O(\log n) space
  2. Directed reachability is known to need Ω(n)\Omega(n) bits
  3. Any reachability algorithm using o(n)o(n) bits must take exponential time
  4. Savitch's theorem decides directed reachability in O(log⁡n)O(\log n) space
Show the answer

A. Undirected ss–tt connectivity can be decided deterministically in O(log⁡n)O(\log n) space

Reingold (2005) decided undirected connectivity in logarithmic space, deterministically. For directed graphs, Savitch's algorithm uses O(log⁡2n)O(\log^2 n) bits but nO(log⁡n)n^{O(\log n)} time, and the best polynomial-time algorithm known uses n/2Θ(log⁡n)n / 2^{\Theta(\sqrt{\log n})} bits.

Further reading

  • R. B. Dial, "Algorithm 360: Shortest-path forest with topological ordering," Communications of the ACM 12(11) (1969), 632–633.
  • I. Pohl, "Bi-directional search," in Machine Intelligence 6 (1971).
  • R. E. Korf & P. Schultze, "Large-scale parallel breadth-first search," Proceedings of the 20th National Conference on Artificial Intelligence (AAAI-05) (2005), 1380–1385.
  • O. Reingold, "Undirected connectivity in log-space," Journal of the ACM 55(4) (2008), article 17; preliminary version at STOC 2005.
  • S. Russell & P. Norvig, Artificial Intelligence: A Modern Approach, 4th ed. (Pearson, 2020), chapter 3.