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 , 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 , 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
| Problem | State | Number of states | Moves per state |
|---|---|---|---|
| A combination lock with 4 wheels | the four digits | 8: turn one wheel up or down | |
| The 8-puzzle | the arrangement of the tiles | reachable | 2 to 4 |
| A grid maze with keys and locked doors | (cell, set of keys held) | 4 | |
| Word ladder | a dictionary word | the dictionary size | up to candidates for words of length |
| Rubik's cube | the position and orientation of every piece | 18 face turns |
The costs follow from the counts. BFS on an implicit graph takes time for reachable states with at most moves each, plus the cost of encoding and hashing states, and memory for the visited set, which is usually what runs out first.
A 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
cells times sets of keys: states, each with 4 moves, so BFS examines at most about moves. With twenty keys it would be 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.
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 distEach edge is relaxed once, when its tail is first popped, so the deque receives at most entries: 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.
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, and , where is the front key:
Each step keeps it. Popping the front leaves keys in . A popped vertex with key pushes key at the front along 0-edges and key at the back along 1-edges. When the last key leaves, the front key becomes and the allowed pair moves up to :
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 , Dial's algorithm (1969) generalizes the deque to buckets indexed by distance. Settle the vertices bucket by bucket; an edge leads at most buckets ahead, so a circular array of buckets suffices, and since no distance exceeds the time is . It beats a binary heap when is small; 0-1 BFS is the case .
Meeting in the middle: bidirectional BFS
Bidirectional search (Pohl, 1971) runs one BFS forward from and one backward from , along reversed edges, and stops when they meet. If every state has successors and is moves away, one search explores about states, while two searches that meet halfway explore about : with and , roughly states instead of . 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.
No meeting so far means is far. If , take a shortest path and its vertex at distance from . The forward search has reached , and is within of , so the backward search has reached it too: a common vertex. Hence
The meeting vertex closes the gap. has and backward distance at most , so
Equality holds throughout (in particular ), so every meeting vertex found while expanding this layer gives the same, optimal length, and the first one will do.
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 -1Expanding 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 and the saving is exponential. On an open grid the cells within distance number only , so the layers grow linearly and halving the radius saves much less. The same meet-in-the-middle idea solves subset sum in instead of : see the lesson Meet in the Middle.
On an open grid, is 100 steps from . One BFS explores every cell within distance 100 of ; bidirectional BFS explores the cells within distance 50 of and within distance 50 of . Roughly what percentage of the one-directional work is that?
Show the answer
50 %
One search covers cells, and two searches of radius 50 cover : 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 states to about .
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 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 word operations on -bit words (see Bit-Parallel Algorithms).
How little memory can reachability use at all? BFS needs bits. Savitch (1970) decides whether is reachable from in a directed graph with bits, by recursing on "is there a path of length at most through some middle vertex?", but in time. For undirected graphs Reingold (2005) needs only bits, which also means polynomial time. For directed graphs, the best known polynomial-time algorithm still uses bits (Barnes, Buss, Ruzzo & Schieber, 1998), barely below .
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 ; Dial's buckets extend this to integer weights up to in .
- Bidirectional BFS that expands whole layers may stop at the first meeting, with . It turns into about 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 states. Undirected connectivity fits in 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.
A 0-1 BFS marks each vertex as finished the first time it is pushed, as plain BFS does. On the edges of weight 1, of weight 0 and of weight 0, what distance does it report for ?
- 0, the true distance
- 1
- 2
- It never reaches
Show the answer
B. 1
Popping pushes to the back with distance 1 and to the front with distance 0. Popping finds the free edge to , but is already marked, so the cheaper route is ignored and keeps 1 instead of 0. In 0-1 BFS, as in Dijkstra's algorithm, a vertex is final only when it is popped.
"Fewest steps from S to E in a grid, where you may break through at most walls." Which BFS state is correct?
- The cell alone
- (cell, direction of the last move)
- (cell, number of walls broken so far)
- (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: of them. BFS over these states finds the fewest steps.
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 ?
- At most 6, so the search must continue to be sure
- Exactly 5
- Either 6 or 7
- Exactly 6
Show the answer
D. Exactly 6
No common vertex after those layers means , and the meeting vertex lies on a path of length . So , and the search can stop at once.
BFS keeps bits for its visited set. Which statement about reachability in less memory is true?
- Undirected – connectivity can be decided deterministically in space
- Directed reachability is known to need bits
- Any reachability algorithm using bits must take exponential time
- Savitch's theorem decides directed reachability in space
Show the answer
A. Undirected – connectivity can be decided deterministically in space
Reingold (2005) decided undirected connectivity in logarithmic space, deterministically. For directed graphs, Savitch's algorithm uses bits but time, and the best polynomial-time algorithm known uses 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.