Module contents
Lesson 1 of 23Review 75 min

State spaces and uninformed search

A dense review of formulating problems as implicit state-space searches and of classical uninformed algorithms: breadth-first, uniform-cost, depth-first, iterative deepening and bidirectional search. Analyze completeness, optimality and complexity rigorously in terms of branching factor b, depth d and the ratio C*/ε, and build the generic search engine reused throughout the module.

After this lesson you can

  • Formulate a problem in terms of states, initial state, actions, transition model, goal test and cost, and estimate its state-space size.
  • Distinguish tree and graph search and decide when the explored set is worth its memory cost.
  • Derive completeness, optimality and complexity of BFS, DFS, uniform-cost and iterative deepening in terms of b, d, m and C*/ε.
  • Implement a generic search engine parameterized by frontier structure and instrumented with counters.
  • Justify why iterative deepening is the preferred blind algorithm when the space is large and solution depth unknown.

Before you start

In 1975 Allen Newell and Herbert Simon jointly received the Turing Award, and their lecture, published the following year as “Computer Science as Empirical Inquiry: Symbols and Search,” summarized twenty years of artificial intelligence in two hypotheses. The first, the physical symbol system hypothesis, says that “a physical symbol system has the necessary and sufficient means for general intelligent action.” The second, the heuristic search hypothesis, describes what that system does when solving a problem: solutions are represented as symbol structures, and the system exercises intelligence “by searching, that is, by generating and progressively modifying symbol structures until it produces a solution structure.” In the same paper they define a problem with two parts: a test that recognizes solutions and a generator of candidates.

Half a century later, that description is still literally true of a huge part of working computing. A route planner, a SAT solver, a chess engine, a robot planner and AlphaZero’s search loop generate candidates, test them and decide which to look at next. What differs is the order in which candidates are generated and how much is remembered of what has already been seen. This lesson studies algorithms that know nothing about the problem beyond its rules, called blind or uninformed search: breadth-first, uniform-cost, depth-first, iterative deepening and bidirectional search. They provide the skeleton on which the next lesson builds A* and the rest of the module; their analysis (completeness, optimality, time and memory in terms of a few parameters) is the template for analyzing any search.

Before formalizing anything, watch the four competitors work on the same problem.

Four searches, one maze

A robot must go from the black cell to the red cell of a grid. Each step onto a free cell costs 1 and each step onto mud costs 5. All four searches advance on the same clock: one tick for each node they generate. This compares what matters, the work, rather than the wall time of a particular implementation.

InteractiveA race of frontiers on a grid
Breadth-first (BFS)26 steps · cost 38
gen. 109exp. 106peak mem. 109
Uniform-cost30 steps · cost 30
gen. 113exp. 110peak mem. 113
Depth-first (DFS)50 steps · cost 50
gen. 67exp. 56peak mem. 67
Iterative deepening26 steps · cost 38
gen. 3315exp. 2875peak mem. 36limit 26
  • expanded (in IDDFS, darker for more visits in the iteration)
  • frontier
  • returned path
  • current IDDFS branch
  • mud, cost 5
Tool
3315 nodes
Nodes generated by each search3315
Optimal cost (mud = 5)30
BFS finds the fewest-step path (26) but costs 38; uniform-cost takes 30 steps and costs 30. DFS returns 50 steps where 26 would suffice. IDDFS generates 3315 nodes (30.4 times BFS) with peak memory 36 versus 109.
Each panel runs a search on the same map. Blue: expanded cells; aqua: the frontier; magenta: the returned path. In iterative deepening (IDDFS), blue gets darker the more often a cell has been visited in the current iteration, and the violet line is the branch being explored. The clock is logarithmic so searches taking a hundred nodes and searches taking a hundred thousand are visible together. Press ‘Race’ and compare the paths and costs. Then paint mud over the uniform-cost path, switch to the acyclic maze and open room, and move the goal far from and close to the start.

In the maze with mud (the initial map), the four personalities explained in the rest of the lesson emerge:

  • Breadth-first (BFS) finds the path with the fewest steps, 26, but crosses the mud and costs 38. It counts steps, not costs.
  • Uniform-cost takes a 30-step detour costing 30, the optimum. It generates almost as many nodes as BFS (113 versus 109).
  • Depth-first (DFS) generates fewer nodes than any other (67) and returns a 50-step path: it reaches the goal along the first corridor that leads there, with no quality criterion.
  • Iterative deepening returns the same path as BFS but generates 3315 nodes, thirty times more, because it repeats the search with limits 0, 1, 2, …, 26. In return, it never holds more than 36 nodes in memory.

The other two maps show the extremes. In the acyclic maze there is only one simple path between two cells and all four searches return the same 42-step path; iterative deepening pays its worst relative overhead there (1679 nodes versus 69), because in a corridor the branching factor is almost 1 and repeating upper levels costs as much as the last. In the open room, iterative deepening exceeds 120 000 nodes without reaching the goal, 20 steps away, while BFS finds it with 175: without memory of what was visited, each of the many different simple paths to a cell is a different node. That is the price of not remembering, and understanding it means understanding the difference between searching a tree and searching a graph.

Formulating a problem

The difference from graphs used in shortest-path algorithms is one of scale and representation. The state space is almost never stored: it is implicit. All that exists in memory is the initial state and a function that enumerates successors given a state. The graph is generated on demand, and most of it is never generated. Therefore the analysis does not use the numbers of vertices ∣V∣\abs{V} and edges ∣E∣\abs{E}, which can be astronomical or infinite, but four local parameters:

  • bb, the branching factor: the maximum number of successors of a state;
  • dd, the depth of the shallowest solution: the smallest number of actions in a solution;
  • mm, the maximum depth of any path in the space (possibly ∞\infty);
  • C∗C^* and ε\eps: the optimal cost and a positive lower bound on action costs, c≥ε>0c \ge \eps > 0.

The art of abstraction

Formulating means deciding what to forget. A robot moving between rooms has continuous position, orientation, wheel speeds and battery level; if the question is which doors to go through, the state can be “the room it is in” and the action “cross this door.” The abstraction is valid if every abstract solution can be refined into a solution to the real problem (crossing a door can be executed by a low-level controller), and useful if executing each abstract action is easier than the original problem. A poor choice is costly in both directions: too much detail explodes the space, and too little makes abstract solutions impossible to execute. When the state is continuous, like the configuration of a robotic arm, search moves to configuration space, and the ideas of this lesson reappear with sampling instead of enumeration.

The size of the space: the 8-puzzle

The 8-puzzle is an 3×33 \times 3 board with eight numbered tiles and a blank; an action slides a neighboring tile into the blank. The state is the arrangement of tiles: a permutation of the nine symbols. Actions depend only on the blank’s location (2 in a corner, 3 at an edge, 4 in the center), so b=4b = 4 and the mean number of actions per blank position is 24/9≈2.6724/9 \approx 2.67.

There are 9!=362 8809! = 362\,880 arrangements, but not all are reachable. Read the eight tiles row by row, ignoring the blank, and count inversions, pairs of tiles in reverse order.

Proof

A horizontal move swaps the blank with a tile in the same row: the sequence read row by row without the blank does not change. A vertical move takes a tile three places forward or back in reading order, jumping over the two tiles between them. Its relative position with respect to each of those two reverses, so the number of inversions changes by −2-2, 00 or +2+2. States divide into two equal-sized parity classes (swapping the first two tiles is a parity-changing bijection), and moves do not leave the class.

∎

The converse, that all states of the same parity are reachable, was proved by Johnson and Story in 1879 for the 15-puzzle; here we check it by brute force. The cell traverses the entire space reachable from the goal in breadth-first order and counts states by distance.

[ ]Counting the 8-puzzle state spaceBrowser
from collections import deque
from math import factorial

# vecinos del hueco por posición, y anchura sobre estados codificados como cadenas de 9 caracteres
NB = {z: [j for j in (z - 3, z + 3) if 0 <= j < 9] + [j for j in (z - 1, z + 1) if j // 3 == z // 3] for z in range(9)}

def mover(s, z, j):
    t = list(s); t[z], t[j] = t[j], t[z]
    return "".join(t)

def capas(inicio):
    dist = {inicio: 0}
    cola = deque([inicio])
    while cola:
        s = cola.popleft()
        z = s.index("0")
        for j in NB[z]:
            t = mover(s, z, j)
            if t not in dist:
                dist[t] = dist[s] + 1
                cola.append(t)
    return dist

dist = capas("123456780")
cuenta = [0] * (max(dist.values()) + 1)
for d in dist.values():
    cuenta[d] += 1
print("estados alcanzables:", len(dist), " = 9!/2 =", factorial(9) // 2)
print("distancia máxima a la meta:", len(cuenta) - 1, " estados a esa distancia:", [s for s, d in dist.items() if d == len(cuenta) - 1])
print("estados por distancia:", cuenta)
print("factor de ramificación medio (posiciones del hueco):", sum(len(v) for v in NB.values()) / 9)
print("15-puzzle: 16!/2 =", factorial(16) // 2)

# el árbol de búsqueda desde el hueco en el centro: cada camino lo fija el hueco, así que el número de nodos a
# profundidad k es el número de paseos de longitud k del hueco por la rejilla 3x3 (con y sin deshacer)
def paseos(z0, K, sin_deshacer):
    c = {(z0, None): 1}
    total = [1]
    for _ in range(K):
        n = {}
        for (z, previo), v in c.items():
            for j in NB[z]:
                if sin_deshacer and j == previo:
                    continue
                n[(j, z)] = n.get((j, z), 0) + v
        c = n
        total.append(sum(c.values()))
    return total

centro = capas("123405678")
for K in (8, 30):
    distintos = sum(1 for d in centro.values() if d <= K)
    print(f"hasta profundidad {K:>2}: árbol {sum(paseos(4, K, False)):>17,}   sin deshacer {sum(paseos(4, K, True)):>11,}   estados distintos {distintos:>7,}")
print("distancia máxima desde el hueco en el centro:", max(centro.values()))
print("cubo de Rubik: 8! 3^7 12! 2^11 / 2 =", factorial(8) * 3**7 * factorial(12) * 2**11 // 2)

There are exactly 181 440181\,440 states, and the farthest from the goal are 31 moves away: there are two, and no optimal search will ever need more depth. Notice the distribution’s shape: it grows almost geometrically up to distance 22 and then falls, because the space is finite and runs out. Initial geometric growth is the regime modeled by bb and dd; final saturation is what asymptotic analysis ignores and what makes everything work in small spaces. Scale jumps are brutal: the 15-puzzle has 16!/2≈1.05×101316!/2 \approx 1.05\times 10^{13} reachable states and Rubik’s cube has 43 252 003 274 489 856 000≈4.3×101943\,252\,003\,274\,489\,856\,000 \approx 4.3\times 10^{19}. In 2010, Rokicki, Kociemba, Davidson and Dethridge proved that every cube state can be solved in 20 moves or fewer, using decades of CPU time and considerable symmetry; no blind search comes close to those numbers.

Search tree versus state graph

A search algorithm manipulates nodes, not states. A node is a state plus the history of how it was reached: its parent node, the action applied, path cost gg and depth. Nodes form a rooted tree at the initial state, the search tree; two distinct nodes can contain the same state if reached by two paths. The frontier is the set of nodes generated but not yet expanded, and expanding a node applies all actions and generates its children.

All blind algorithms use the same loop with a different frontier:

  1. Put the initial state’s node in the frontier.
  2. While the frontier is not empty, remove a node according to the frontier policy.
  3. If its state is a goal, return the path. Otherwise, expand it and add its children to the frontier.

With a FIFO queue it is breadth-first, with a stack it is depth-first, and with a priority queue ordered by gg it is uniform-cost. This is the same scheme as graph traversal, with two differences: the graph is not given in advance and traversal stops at the goal.

Repeated nodes come from two sources. Cycles return to a state at an earlier level: in the 8-puzzle, undoing the last move. Transpositions reach the same state via different paths of the same length, such as moving two independent tiles in either order. In a cyclic space, tree search with a stack does not terminate, and with a queue it terminates but explores a tree whose size grows like bdb^d even if there are only a handful of distinct states.

InteractiveDuplicates in the 8-puzzle
12345678
Root: the blank is in the center. Each ring is one tree level; a sector’s angle is proportional to its descendants in the last ring.
  • new state
  • repeated from an earlier level (cycle)
  • repeated at the same level (transposition)
  • full tree
  • tree without undo
  • 9!/2 = 181 440
Search
7
Tree nodes through this depth0
Distinct states0
Repeated: cycles0
Repeated: transpositions0
Fraction of repeated nodes0.0 %
0 % of the tree consists of repeated states, mostly from undoing moves.
The 8-puzzle search tree from the state with the blank in the center, shown in rings: ring kk contains nodes at depth kk, and each sector's angle is proportional to its descendants in the last ring. Blue: first occurrence of a state; red: repetition of a state from an earlier level (cycle); orange: repetition at the same level by another path (transposition). Hover over a sector to see the board and highlight all its copies. Compare the three modes: full tree, tree without undoing the last move, and graph with a reached table. The chart below gives exact counts up to depth 30, calculated in the interactive itself.

The numbers in the interactive and previous cell tell the story. Up to depth 8, the full tree has 9361 nodes for 337 distinct states: 96% of the tree is repeated work, almost all from undoing moves. Forbidding just that (comparing the child with the grandparent, with no extra memory) leaves 373 nodes, barely 11% above the graph. This is no accident: apart from going back and forth, the shortest cycle in the 8-puzzle has 12 moves (the blank circles an 2×22 \times 2 block three times and the three tiles in the block return to their places), so without undoing there is no duplicate until depth 6, where two length-6 paths meet. But transpositions accumulate: up to depth 30, the tree without undoing has 68 900 96568\,900\,965 nodes, 380 times the 181 440181\,440 states in the space, and the full tree has 8.0×10138.0\times 10^{13}.

When a reached table pays off

The table costs memory proportional to the number of distinct states reached, and also requires each state to be storable in a hash table (hash table): an immutable representation with coherent equality and hash, such as a tuple, string or integer encoding the state. The practical criterion is to compare two numbers at the search horizon: the number of paths of length ≤d\le d and the number of distinct states at distance ≤d\le d.

  • If the two are of the same order (few short cycles and transpositions, or spaces with tree structure), the table saves little and may not fit in memory. Use tree search with cheap pruning: do not return to the parent, or do not repeat a state on the current path (path cycle checking, costing O(d)\bigO(d) memory).
  • If the number of paths grows much faster than the number of states (grids, deep puzzles, games with transpositions), the table is indispensable, even if fixed-size and remembering only part of what was seen, like game engines’ transposition tables.

In the earlier race, the open room takes the second case to an extreme: the grid has 187 cells, but the number of simple paths grows exponentially with length, and iterative deepening, whose cycle check prunes only self-intersecting paths, exceeds 120 000 nodes before finishing the iteration with limit 12.

Proof

By induction on kk: when the first node at depth kk is removed, the frontier contains only nodes at depths kk and k+1k + 1, and every state at distance j≤kj \le k from the start has already been reached by a node at depth exactly jj. This is the FIFO queue invariant; the inductive step follows because the children of nodes at depth kk are exactly the states at distance ≤k+1\le k + 1 not already reached. Thus the first goal state generated has minimum depth, and there is no need to wait to expand it: any node generated later has greater or equal depth. If actions all cost cc, a path’s cost is cc times its length, and minimum length is minimum cost. As level kk has at most bkb^k nodes and the search goes no deeper than level dd, at most ∑k=1dbk\sum_{k=1}^d b^k nodes are generated; all stay in the reached table, so memory is of the same order.

∎

The cost is memory. With b=10b = 10 and d=10d = 10, BFS stores on the order of 101010^{10} nodes; at 100 bytes per node that is a terabyte. Time can be waited out; memory cannot.

What if costs differ? Then the path with fewest actions need not be the cheapest, as the mud in the race showed. We must expand by cost rather than depth.

You will prove optimality in the guided exercise, starting from the invariant that nodes are expanded in nondecreasing order of gg. The complexity bound has a short proof worth seeing, because it explains why the exponent is not dd.

Proof

UCS stops when it expands a goal, and the first it expands has g=C∗g = C^*. Since nodes leave in nondecreasing order of gg, every expanded node has g≤C∗g \le C^*. A node at depth kk has g≥kεg \ge k\eps, so expanded nodes have depth k≤C∗/εk \le C^*/\eps, that is, k≤⌊C∗/ε⌋k \le \lfloor C^*/\eps \rfloor, and generated nodes at most one more. The number of nodes at depth ≤1+⌊C∗/ε⌋\le 1 + \lfloor C^*/\eps \rfloor is O(b1+⌊C∗/ε⌋)\bigO(b^{1 + \lfloor C^*/\eps \rfloor}). The same bound gives completeness: before expanding a goal, only the finitely many nodes with g≤C∗g \le C^* can be expanded.

∎

The exponent depends on the ratio between optimal cost and the smallest cost, not on the solution depth. If all actions cost 1, C∗=dC^* = d and the bound is bd+1b^{d+1}: one level more than BFS because the test is on expansion. But if actions costing 0.010.01 coexist with actions costing 1, UCS explores sequences of cheap irrelevant actions in full detail before taking an expensive step toward the goal: with C∗=10C^* = 10 and ε=0.01\eps = 0.01, the exponent is 1001. And the assumption ε>0\eps > 0 cannot be weakened to “positive costs”: with costs 1/2,1/4,1/8,…1/2, 1/4, 1/8, \dots along an infinite path, total cost never exceeds 1 and UCS may expand that path forever without reaching a goal costing 2.

Where to apply the goal test

BFS tests on generation and UCS on expansion, and the difference is not stylistic. For BFS testing on generation is correct (everything generated later is deeper) and saves the entire last level, the most expensive. For UCS it is incorrect: a goal state appearing in the frontier does not mean its gg is minimum, because the frontier may contain a cheaper node from which the goal is reached by a cheap action. The smallest example is a graph with S→GS \to G costing 10, and S→AS \to A and A→GA \to G costing 1. Expanding SS generates AA with g=1g = 1 and GG with g=10g = 10; testing on generation returns S→GS \to G at cost 10, although S→A→GS \to A \to G costs 2. You will check this in the lab.

The exact relationship with Dijkstra

UCS is Dijkstra’s algorithm applied to an implicit graph and stopped as soon as the goal comes out. Vertices are removed in the same order (apart from ties), and both rely on the same invariant. The differences are engineering details, but they matter at this scale:

  • Textbook Dijkstra puts every vertex in the queue at distance ∞\infty and uses decrease-key. This requires knowing the whole graph and allocating memory for it. UCS inserts only what it generates, and what is never generated takes no space.
  • Instead of decrease-key, UCS usually inserts a new entry and discards stale ones on removal (lazy insertion). With a binary heap both variants cost O(log⁡n)\bigO(\log n) per operation, but the lazy one avoids maintaining position indices.
  • Dijkstra calculates distances to all vertices; UCS stops at the goal.

In 2011 Ariel Felner argued in a paper with the eloquent title “Position Paper: Dijkstra’s Algorithm versus Uniform Cost Search or a Case Against Dijkstra’s Algorithm” that the UCS formulation is what should be taught and used in large spaces, because the textbook version is inapplicable to implicit graphs.

Depth-first, depth-limited and iterative deepening

DFS sacrifices everything except memory. It is not optimal: it returns the first path it finds, whatever its length; in the 8-puzzle, graph DFS solves a 2-move problem with a path of almost fifty thousand, as the lab will show. It is not complete as tree search in an infinite space (it can descend forever down a branch without goals) or, without cycle checking, in a cyclic space (it can loop indefinitely). Its time is O(bm)\bigO(b^m), which can be much worse than bdb^d or infinite. But its memory is linear: in a tree it stores only the current path and each path node’s pending siblings, O(bm)\bigO(bm) nodes, or O(m)\bigO(m) with backtracking. The graph version loses this advantage because the reached table grows as in BFS.

Depth-limited search cuts branches at depth ℓ\ell: it treats nodes at depth ℓ\ell as if they had no children. It always terminates, using O(bℓ)\bigO(b\ell) memory and O(bℓ)\bigO(b^\ell) time, but fails if ℓ<d\ell < d and is not optimal if ℓ>d\ell > d. It has two kinds of failure that must be distinguished: “I cut off some branch at the limit” (there may be a solution deeper down) and “I exhausted the space without cutting anything” (there is no solution).

The first reaction to IDDFS is that it wastes work: iteration ℓ\ell regenerates everything generated by ℓ−1\ell - 1. The second, after doing the arithmetic, is that it does not matter.

InteractiveThe exact cost of repeating levels
BFSBFS: 9 840 nodes9 840IDDFSiteration with limit 1: 3 nodesiteration with limit 2: 12 nodesiteration with limit 3: 39 nodesiteration with limit 4: 120 nodesiteration with limit 5: 363 nodesiteration with limit 6: 1 092 nodes6iteration with limit 7: 3 279 nodes7last iteration (limit 8): 9 840 nodes814 748linear scale; numbers inside the IDDFS bar are iteration limits
  • N_ID / N_BFS
  • b/(b−1)
  • BFS: one pass to dd
  • previous IDDFS iterations (repeated work)
  • asymptote b/(b−1)b/(b-1)
3.0
8
NBFS=b+⋯+bdN_{\mathrm{BFS}} = b + \dots + b^d9 840
NIDN_{\mathrm{ID}}14 748
Repeated work NID−NBFSN_{\mathrm{ID}} - N_{\mathrm{BFS}}4 908
NID/NBFSN_{\mathrm{ID}} / N_{\mathrm{BFS}}1.4988
Limit b/(b−1)b/(b-1)1.5000
Peak memory: BFS ≈bd\approx b^d versus IDDFS ≈bd\approx bd6 561 / 24
With b=3.0b = 3.0, IDDFS generates 49.9% more nodes than BFS.
Explicit model: a uniform tree with branching factor bb and the solution at the last node of level dd (the worst case). The blue bar is what BFS generates; the IDDFS bar adds in orange all iterations preceding the last, numbered by their limit. Below is their ratio for each dd and its asymptote b/(b−1)b/(b-1). Set bb to 10 and 2, and dd to 1 and 25. Enable the third bar: BFS testing on expansion.
Proof

The iteration with limit ℓ\ell generates the complete tree to depth ℓ\ell, that is, NBFS(ℓ)N_{\mathrm{BFS}}(\ell) nodes; summing, level kk is generated in iterations ℓ=k,…,d\ell = k, \dots, d, that is, d+1−kd + 1 - k times, giving the second expression. For the third, use the geometric series NBFS(ℓ)=bb−1(bℓ−1)N_{\mathrm{BFS}}(\ell) = \frac{b}{b-1}(b^\ell - 1):

∑ℓ=1dNBFS(ℓ)=bb−1(∑ℓ=1dbℓ−d)=bb−1(NBFS(d)−d).\sum_{\ell=1}^d N_{\mathrm{BFS}}(\ell) = \frac{b}{b-1}\Big(\sum_{\ell=1}^d b^\ell - d\Big) = \frac{b}{b-1}\big(N_{\mathrm{BFS}}(d) - d\big).

Dividing by NBFS(d)N_{\mathrm{BFS}}(d) gives bb−1(1−d/NBFS(d))\frac{b}{b-1}\big(1 - d/N_{\mathrm{BFS}}(d)\big), which is less than b/(b−1)b/(b-1) and tends to it because NBFS(d)N_{\mathrm{BFS}}(d) grows exponentially.

∎

The intuition is in the orange bar: in an exponentially growing tree the last level outweighs all previous ones together, and all previous iterations sum to approximately 1/(b−1)1/(b-1) times the last. With b=10b = 10, IDDFS generates at most 11% more than BFS; with b=2b = 2, twice as much. If BFS tests on expansion and generates level d+1d + 1, IDDFS (which does not generate children of nodes at the limit) is even cheaper than BFS: the ratio tends to 1/(b−1)1/(b-1), so it wins for every b>2b > 2, and with b=10b = 10 and d=8d = 8 generates 89% less. The bad case is b→1b \to 1: in a corridor each iteration costs as much as the previous one and the total is quadratic, ≈d2/2\approx d^2/2, as you saw in the acyclic maze.

Completeness and optimality are inherited from BFS: the iteration with limit ℓ\ell finds a solution if and only if one exists at depth ≤ℓ\le \ell, and iterations increase one by one, so the first solution appears in iteration dd and has depth dd. Time follows from the previous theorem; memory is that of depth-limited search with ℓ=d\ell = d. Richard Korf proved in 1985 that among brute-force tree searches, iterative deepening is asymptotically optimal simultaneously in time, memory and the length of the solution returned; the idea was already used in chess programs and you will see it become the main engine loop in iterative game search and combined with heuristics in IDA*. That is why IDDFS is the preferred blind algorithm when the space is large and solution depth unknown: it has BFS completeness and optimality with DFS memory, paying a constant factor for them.

If you search forward from the start and backward from the goal at once, stopping when the two searches meet, each only has to reach halfway: 2bd/22 b^{d/2} instead of bdb^d. With b=10b = 10 and d=8d = 8, that is 22 22022\,220 nodes versus 111 111 110111\,111\,110.

The saving is spectacular, but has three conditions:

  1. Actions must be invertible: one must be able to calculate a state’s predecessors. In the 8-puzzle and grids this is trivial (actions are reversible); on a road graph with one-way streets it suffices to reverse edges; in other domains the predecessor set is huge or difficult to enumerate.
  2. The goal must be a specific state, or a small explicit set of states. If the goal is a test (“the opposing king is checkmated,” “the eight queens do not attack one another”), there is nowhere to start searching backward.
  3. The stopping condition is not “they met.” This is the classic mistake, and it depends on whether there are costs.
Proof

Consider the moment the forward side expands its level kk: it has reached exactly the states at distance ≤k\le k from s0s_0 (plus those at distance k+1k + 1 that it is generating), and the backward side, which expands only complete levels, has reached exactly the states at distance ≤j\le j from the goal tt. Since there was no earlier meeting, no state at distance ≤k\le k from s0s_0 is at distance ≤j\le j from tt, and therefore dist(s0,t)≥k+j+1\mathrm{dist}(s_0, t) \ge k + j + 1. If vv is now generated at distance k+1k + 1 from s0s_0 and vv was reached backward at distance j′≤jj' \le j, the path found has length k+1+j′≤k+j+1k + 1 + j' \le k + j + 1. Combined with the lower bound, its length is exactly dist(s0,t)\mathrm{dist}(s_0, t).

∎

The complete-level assumption is not decorative: if we alternate node by node, the backward side may have reached some states of level j+1j + 1 and the first meeting may give a path one step longer than optimal. With costs, the problem is worse.

Proof

Always μ≥C∗\mu \ge C^*, because it is the cost of a real path. Suppose μ>C∗\mu > C^* at stopping and take an optimal path s0=x0,x1,…,xr=ts_0 = x_0, x_1, \dots, x_r = t. By the UCS invariant, every state at distance less than topF\mathrm{top}_F from s0s_0 has been expanded forward with its exact distance, and likewise backward with topB\mathrm{top}_B. For every xix_i on the optimal path, dist(s0,xi)+dist(xi,t)=C∗<μ≤topF+topB\mathrm{dist}(s_0, x_i) + \mathrm{dist}(x_i, t) = C^* < \mu \le \mathrm{top}_F + \mathrm{top}_B, so dist(s0,xi)<topF\mathrm{dist}(s_0, x_i) < \mathrm{top}_F or dist(xi,t)<topB\mathrm{dist}(x_i, t) < \mathrm{top}_B. Let xix_i be the last on the path with dist(s0,xi)<topF\mathrm{dist}(s_0, x_i) < \mathrm{top}_F (it exists because x0x_0 satisfies 0<topF0 < \mathrm{top}_F except in the trivial case). If i=ri = r, the goal is expanded forward with its exact distance and μ≤C∗\mu \le C^*. Otherwise, xi+1x_{i+1} has dist(xi+1,t)<topB\mathrm{dist}(x_{i+1}, t) < \mathrm{top}_B and is expanded backward with its exact distance. When the latter of the two was expanded, edge xi→xi+1x_i \to x_{i+1} was relaxed with both distances already exact, and μ\mu fell to at most dist(s0,xi)+c(xi,xi+1)+dist(xi+1,t)=C∗\mathrm{dist}(s_0, x_i) + c(x_i, x_{i+1}) + \mathrm{dist}(x_{i+1}, t) = C^*. Contradiction.

∎

The tempting rule, “stop as soon as a state is closed from both sides and return the path through it,” is incorrect: the first state closed by both sides need not lie on an optimal path, which may cross from one side to the other along an edge between a state closed only forward and one closed only backward.

InteractiveTwo frontiers meet
Uniform-costcost 20
Bidirectionalcost 24
  • expanded forward
  • expanded backward
  • returned path
  • optimal path (if different)
  • mud, cost 5
Stopping rule
154
Expanded: uniform-cost134
Expanded: bidirectional (forward + backward)75 + 79
μ\mu (best complete path seen)20
topF+topB\mathrm{top}_F + \mathrm{top}_B25
Returned / optimal cost24 / 20
The first cell closed by both sides need not lie on an optimal path: the path through it costs 24, even though the search had already seen one costing μ=20\mu = 20.
On the left, uniform-cost search from the start; on the right, bidirectional uniform-cost search, blue forward and aqua backward, with the same number of expansions. With the ‘first meeting’ rule, search stops when a cell already closed by one side leaves the other and returns the path through it: on irregular terrain it costs 24 and the optimum, shown dashed, costs 20, although the search had already seen it (μ=20\mu = 20). Change to the rule topF+topB≥μ\mathrm{top}_F + \mathrm{top}_B \ge \mu: the path is optimal. Then switch to the open room and compare explored areas.

The interactive also shows the limit of the savings. On irregular terrain the correct version expands 117 cells versus 134 for ordinary uniform-cost search, and the incorrect rule reaches 154. There is no bd/2b^{d/2}: on a grid the number of cells at distance ≤r\le r grows like r2r^2, not brb^r, and two disks of radius r/2r/2 occupy half the area of one of radius rr. In general, in a space with polynomial growth of degree DD, bidirectional search saves a factor 2D−12^{D-1}; exponential savings exist only when the number of states grows exponentially with distance. In the lab you will measure this on both types of graph. Although the idea is old (Ira Pohl analyzed it in 1971), making the two searches actually meet in the middle with costs and heuristics proved subtle: the MM algorithm of Holte, Felner, Sharon and Sturtevant (2016) was the first with that guarantee.

How to choose: a comparison table

AlgorithmComplete?Optimal?TimeMemory
Breadth-first (BFS)yes ⁽ᵃ⁾yes ⁽ᶜ⁾O(bd)\bigO(b^d)O(bd)\bigO(b^d)
Uniform-costyes ⁽ᵃ ᵇ⁾yesO(b1+⌊C∗/ε⌋)\bigO(b^{1 + \lfloor C^*/\eps \rfloor})O(b1+⌊C∗/ε⌋)\bigO(b^{1 + \lfloor C^*/\eps \rfloor})
Depth-first (tree)no ⁽ᵈ⁾noO(bm)\bigO(b^m)O(bm)\bigO(bm)
Depth-limitednonoO(bℓ)\bigO(b^\ell)O(bℓ)\bigO(b\ell)
Iterative deepeningyes ⁽ᵃ⁾yes ⁽ᶜ⁾O(bd)\bigO(b^d)O(bd)\bigO(bd)
Bidirectionalyes ⁽ᵃ ᵉ⁾yes ⁽ᶜ ᵉ⁾O(bd/2)\bigO(b^{d/2})O(bd/2)\bigO(b^{d/2})

(a) if bb is finite; (b) if costs are ≥ε>0\ge \eps > 0; (c) if all actions cost the same, or with the uniform-cost version; (d) complete in finite spaces with cycle checking or as graph search; (e) if both directions are breadth-first, or uniform-cost with the μ\mu stopping condition.

Read as a decision guide:

  • Different costs: uniform-cost (or its bidirectional version with the correct stopping rule). No other blind algorithm guarantees the optimum.
  • Equal costs and enough memory for reached states: graph BFS. If there is also an explicit goal and invertible actions, bidirectional.
  • Equal costs and scarce memory, unknown depth: iterative deepening, with the cheapest pruning that eliminates dominant duplicates (do not return to parent, path cycle checking).
  • Many solutions, all at known depth and none preferred (for example, filling a board): DFS with backtracking, the basis of backtracking search for constraint satisfaction problems.
  • None of the above scales: information about the problem, a heuristic, is needed; this is the next lesson’s topic.

Implementation from scratch

The first lab builds the engine reused by the rest of the module: a Problem class that only describes the problem and a single search function parameterized by the frontier structure (deque, a list as stack or heapq), instrumented with counters for generated and expanded nodes and peak memory.

[ ]A generic search engineBrowser
import heapq
import itertools
from collections import deque


class Problem:
    """Problema de búsqueda: estado inicial, acciones, modelo de transición, objetivo y coste."""

    def __init__(self, initial, goal=None):
        self.initial, self.goal = initial, goal

    def actions(self, s):
        raise NotImplementedError

    def result(self, s, a):
        raise NotImplementedError

    def is_goal(self, s):
        return s == self.goal

    def action_cost(self, s, a, s2):
        return 1


class Node:
    """Nodo del árbol de búsqueda: un estado, el estado padre, la acción que lo generó, g y profundidad.

    Guarda el estado padre, no el nodo padre: en búsqueda en grafo el camino se reconstruye con la tabla
    de alcanzados, y se evitan cadenas de decenas de miles de objetos enlazados (que Pyodide no puede
    liberar sin desbordar su pila).
    """
    __slots__ = ("state", "parent", "action", "g", "depth")

    def __init__(self, state, parent=None, action=None, g=0, depth=0):
        self.state, self.parent, self.action, self.g, self.depth = state, parent, action, g, depth


def expand(problem, node):
    s = node.state
    for a in problem.actions(s):
        s2 = problem.result(s, a)
        yield Node(s2, s, a, node.g + problem.action_cost(s, a, s2), node.depth + 1)


def reconstruct(reached, node):
    """Estados y acciones del camino hasta node, siguiendo los padres en la tabla de alcanzados."""
    states, actions = [node.state], []
    while node.parent is not None:
        actions.append(node.action)
        node = reached[node.parent]
        states.append(node.state)
    return states[::-1], actions[::-1]


def search(problem, frontier="fifo", early_goal=None, max_generated=10**6):
    """Búsqueda en grafo con un único motor: la frontera decide el algoritmo.

    fifo -> anchura, lifo -> profundidad, priority -> coste uniforme (montículo por g).
    Devuelve (nodo solución o None, estadísticas). Las estadísticas incluyen el camino ("path",
    "actions") y la memoria pico: nodos en la tabla de alcanzados más entradas obsoletas del montículo.
    """
    if early_goal is None:
        early_goal = frontier != "priority"
    st = {"generated": 1, "expanded": 0, "peak": 1}
    root = Node(problem.initial)
    reached = {problem.initial: root}

    def done(node):
        st["path"], st["actions"] = reconstruct(reached, node)
        return node, st

    if problem.is_goal(root.state):
        return done(root)
    tie = itertools.count()
    if frontier == "fifo":
        F = deque([root]); pop, push = F.popleft, F.append
    elif frontier == "lifo":
        F = [root]; pop, push = F.pop, F.append
    else:
        F = [(0, next(tie), root)]
        pop = lambda: heapq.heappop(F)[2]
        push = lambda n: heapq.heappush(F, (n.g, next(tie), n))
    stale = 0
    while F:
        node = pop()
        if reached[node.state] is not node:      # entrada obsoleta: ya hay un camino mejor
            stale -= 1
            continue
        if not early_goal and problem.is_goal(node.state):
            return done(node)
        st["expanded"] += 1
        for child in expand(problem, node):
            old = reached.get(child.state)
            if old is not None and (frontier != "priority" or old.g <= child.g):
                continue                          # duplicado que no mejora: se descarta
            if old is not None:
                stale += 1                        # la entrada vieja sigue en el montículo
            reached[child.state] = child
            st["generated"] += 1
            if early_goal and problem.is_goal(child.state):
                return done(child)
            push(child)
        st["peak"] = max(st["peak"], len(reached) + stale)
        if st["generated"] > max_generated:
            st["aborted"] = True
            return None, st
    return None, st


def iddfs_parent(problem, max_depth=50):
    """Profundización iterativa en árbol que solo evita volver al estado padre."""
    st = {"generated": 0, "expanded": 0, "peak": 0, "per_iter": []}

    def dls(node, limit, alive):
        if problem.is_goal(node.state):
            return node
        if limit == 0:
            return None
        st["expanded"] += 1
        kids = [c for c in expand(problem, node) if c.state != node.parent]
        st["generated"] += len(kids)
        alive += len(kids)
        st["peak"] = max(st["peak"], alive)
        for k, child in enumerate(kids):
            found = dls(child, limit - 1, alive - k)
            if found is not None:
                return found
        return None

    for limit in range(max_depth + 1):
        before = st["generated"]
        st["generated"] += 1                      # la raíz, regenerada en cada iteración
        found = dls(Node(problem.initial), limit, 1)
        st["per_iter"].append(st["generated"] - before)
        if found is not None:
            return found, st
    return None, st


class EightPuzzle(Problem):
    """Estados: tuplas de 9 enteros fila a fila, 0 = hueco. Acciones: hacia dónde se mueve el hueco."""
    MOVES = {"arriba": -3, "abajo": 3, "izquierda": -1, "derecha": 1}

    def __init__(self, initial, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)):
        super().__init__(tuple(initial), tuple(goal))

    def actions(self, s):
        z = s.index(0)
        acts = []
        if z >= 3: acts.append("arriba")
        if z < 6: acts.append("abajo")
        if z % 3 > 0: acts.append("izquierda")
        if z % 3 < 2: acts.append("derecha")
        return acts

    def result(self, s, a):
        z = s.index(0)
        j = z + self.MOVES[a]
        t = list(s)
        t[z], t[j] = t[j], t[z]
        return tuple(t)


p = EightPuzzle((1, 2, 3, 4, 0, 6, 7, 5, 8))
for nombre, frontera in [("anchura", "fifo"), ("profundidad", "lifo"), ("coste uniforme", "priority")]:
    sol, st = search(p, frontera)
    print(f"{nombre:<15} {len(st['actions']):>6} acciones  primeras: {str(st['actions'][:4]):<45}"
          f" generados {st['generated']:>6}  expandidos {st['expanded']:>6}  memoria pico {st['peak']:>6}")

Four engine details deserve attention. States are tuples, not lists: they are keys in the reached table and must be immutable and hashable. The reached[node.state] is not node check recognizes stale heap entries without decrease-key. The tie tie-break counter prevents heapq from comparing two nodes with the same gg, which have no defined order. And each node stores the parent state, not the parent node: the path is reconstructed using the reached table, which already exists, avoiding chains of linked objects as long as the path. This is not cosmetic: the first version of this cell linked nodes, and freeing the chain nearly fifty thousand nodes deep overflowed the Pyodide stack because each freed object recursively freed its parent.

The output is already telling: the starting state is two moves from the goal, breadth-first and uniform-cost find those two moves, and depth-first, with the stack and fixed action order, returns a path of 49 284 moves after generating 170 323 nodes, almost the entire space.

The table, measured

Now the comparison table with real measurements in the 8-puzzle, on three starting states obtained by random moves from the goal. Iterative deepening prunes returns to the parent and has no reached table.

[ ]The table, measured on the 8-puzzleBrowser
import random

def scramble(n_moves, seed):
    """Estado a n_moves movimientos aleatorios de la meta (sin deshacer el último)."""
    rnd = random.Random(seed)
    p = EightPuzzle((1, 2, 3, 4, 5, 6, 7, 8, 0))
    s, prev = p.goal, None
    for _ in range(n_moves):
        a = rnd.choice([a for a in p.actions(s) if p.result(s, a) != prev])
        prev, s = s, p.result(s, a)
    return s

def fila(nombre, sol, st):
    prof = "-" if sol is None else sol.depth
    extra = " (abortado)" if st.get("aborted") else ""
    print(f"  {nombre:<26} prof. {str(prof):>5}  generados {st['generated']:>7}  expandidos {st['expanded']:>7}  memoria pico {st['peak']:>6}{extra}")

for n_moves, seed in [(10, 1), (16, 3), (24, 7)]:
    p = EightPuzzle(scramble(n_moves, seed))
    sol_b, st_b = search(p, "fifo")
    print(f"inicio {p.initial}: solución óptima a profundidad {sol_b.depth}")
    fila("anchura (grafo)", sol_b, st_b)
    fila("coste uniforme (grafo)", *search(p, "priority"))
    if sol_b.depth <= 16:
        sol_i, st_i = iddfs_parent(p)
        fila("prof. iterativa (árbol)", sol_i, st_i)
        it = st_i["per_iter"]
        print(f"  {'':<26} nodos por iteración: {it}")
        print(f"  {'':<26} iteraciones completas (0 a {len(it) - 2}) / la mayor de ellas: {sum(it[:-1]) / it[-2]:.2f}")

Read the table column by column:

  • Depth. All three searches find the optimal solution (10, 16 and 18 moves), because every action costs 1 in the 8-puzzle.
  • Uniform-cost versus breadth-first. With unit costs, UCS is BFS testing on expansion and pays for it: 16 887 nodes generated versus 10 927 at depth 16, because it generates almost the entire level 17 before removing the goal from the heap.
  • Memory. At depth 16, BFS stores 10 926 nodes and iterative deepening 32. That is the whole argument for IDDFS.
  • IDDFS time. It generates 50 851 nodes, 4.7 times BFS. The decomposition explains why. Complete iterations sum to 2.40 times the largest, as predicted by the theorem with the 8-puzzle’s effective branching factor without undoing: every two levels the tree multiplies by almost 3 (21, 37, 69, 133, 213, 373…), about 3≈1.73\sqrt 3 \approx 1.73 per level, and 1.73/0.73≈2.371.73/0.73 \approx 2.37. The rest of the factor comes from lack of memory: the tree without undoing has about twice as many nodes as distinct states at that depth, and graph BFS does not generate them. The last iteration also stops as soon as it finds the goal, and in this case generated only 8847 of the 31 285 nodes in the complete tree to depth 16.

The second lab scenario is a maze with costs: free cells (cost 1), mud (cost 5) and walls, generated with a fixed seed. Here BFS and uniform-cost cease to agree.

[ ]Mazes with costs and the goal testBrowser
class GridProblem(Problem):
    """Laberinto: '#' muro, '~' barro (coste 5), '.' libre. Entrar en una casilla cuesta su terreno."""
    COST = {".": 1, "~": 5}

    def __init__(self, rows, start, goal):
        self.rows = rows
        super().__init__(start, goal)

    def actions(self, s):
        r, c = s
        out = []
        for a, (dr, dc) in (("N", (-1, 0)), ("E", (0, 1)), ("S", (1, 0)), ("O", (0, -1))):
            rr, cc = r + dr, c + dc
            if 0 <= rr < len(self.rows) and 0 <= cc < len(self.rows[0]) and self.rows[rr][cc] != "#":
                out.append(a)
        return out

    def result(self, s, a):
        dr, dc = {"N": (-1, 0), "E": (0, 1), "S": (1, 0), "O": (0, -1)}[a]
        return (s[0] + dr, s[1] + dc)

    def action_cost(self, s, a, s2):
        return self.COST[self.rows[s2[0]][s2[1]]]

rnd = random.Random(4)
n = 40
rows = ["".join("#" if rnd.random() < 0.22 else "~" if rnd.random() < 0.3 else "." for _ in range(n)) for _ in range(n)]
rows[0] = "." + rows[0][1:]
rows[-1] = rows[-1][:-1] + "."
lab = GridProblem(rows, (0, 0), (n - 1, n - 1))

for nombre, kw in [("anchura", dict(frontier="fifo")),
                   ("profundidad", dict(frontier="lifo")),
                   ("coste uniforme, test al expandir", dict(frontier="priority")),
                   ("coste uniforme, test al generar", dict(frontier="priority", early_goal=True))]:
    sol, st = search(lab, **kw)
    print(f"{nombre:<34} pasos {sol.depth:>4}  coste {sol.g:>4}  generados {st['generated']:>5}  expandidos {st['expanded']:>5}")

class GraphProblem(Problem):
    """Grafo explícito: aristas[u] = {v: coste}."""
    def __init__(self, aristas, initial, goal):
        self.aristas = aristas
        super().__init__(initial, goal)
    def actions(self, s):
        return list(self.aristas.get(s, {}))
    def result(self, s, a):
        return a
    def action_cost(self, s, a, s2):
        return self.aristas[s][s2]

atajo = GraphProblem({"S": {"G": 10, "A": 1}, "A": {"G": 1}}, "S", "G")
for early in (False, True):
    sol, st = search(atajo, "priority", early_goal=early)
    print(f"test al {'generar' if early else 'expandir'}: camino {st['path']}, coste {sol.g}")

In the 40×4040 \times 40 maze, BFS returns 78 steps at cost 170; uniform-cost, 88 steps at cost 120, almost 30% cheaper; DFS, 132 steps at cost 296. The two uniform-cost versions agree here, which proves nothing: on a grid, the goal is often first generated from a neighbor already on an optimal path. The minimal graph below shows what testing on generation can cost: it returns the direct path costing 10 instead of the one costing 2.

Checking the iterative deepening formula

The theorem in the previous section is an exact identity, so it can be checked by counting. The uniform tree in the cell puts the goal at the last leaf of level dd, the worst case for both searches.

[ ]Iterative deepening on uniform treesBrowser
class UniformTree(Problem):
    """Árbol uniforme: un estado es la tupla de elecciones desde la raíz; la meta, la última hoja del nivel d."""
    def __init__(self, b, d):
        self.b, self.d = b, d
        super().__init__((), (b - 1,) * d)
    def actions(self, s):
        return range(self.b) if len(s) < self.d else []
    def result(self, s, a):
        return s + (a,)

for b, d in [(2, 12), (4, 7), (10, 4)]:
    arbol = UniformTree(b, d)
    _, st_b = search(arbol, "fifo")
    _, st_i = iddfs_parent(arbol, max_depth=d)
    n_bfs = st_b["generated"] - 1                 # sin la raíz
    n_id = st_i["generated"] - (d + 1)            # sin las d + 1 raíces regeneradas
    formula = b / (b - 1) * (n_bfs - d)
    print(f"b = {b:>2}, d = {d:>2}:  N_BFS = {n_bfs:>6}  N_ID = {n_id:>6}  fórmula b/(b-1)(N_BFS - d) = {formula:>8.1f}"
          f"  cociente = {n_id / n_bfs:.4f}  b/(b-1) = {b / (b - 1):.4f}")

All three rows satisfy the identity node for node, and the ratios (1.9971, 1.3329 and 1.1107) are just below their limits 22, 4/34/3 and 10/910/9, as predicted by factor 1−d/NBFS1 - d/N_{\mathrm{BFS}}.

Bidirectional search versus networkx

The second lab implements bidirectional BFS with the theorem’s stopping condition (complete levels, the side with the smaller frontier) and validates it against nx.shortest_path_length and nx.bidirectional_shortest_path on two families of random graphs: geometric graphs (points in the unit square connected if their distance is less than rr), which grow like a disk, and random 3-regular graphs, which are expanders and grow exponentially. The geometric graphs are generated with numpy following the same construction as nx.random_geometric_graph (uniform points and edges between those less than rr apart), because that function searches for neighbors with a scipy k-d tree or, if scipy is not loaded, a double loop in Python, and here one vectorized operation on 120021200^2 pairs suffices.

[ ]Bidirectional BFS on random graphsBrowser
import numpy as np
import networkx as nx

def bfs_uni(G, s, t):
    """BFS con test al generar; devuelve (distancia, expandidos)."""
    if s == t:
        return 0, 0
    dist = {s: 0}
    cola = deque([s])
    expandidos = 0
    while cola:
        u = cola.popleft()
        expandidos += 1
        for v in G[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                if v == t:
                    return dist[v], expandidos
                cola.append(v)
    return None, expandidos

def bfs_bi(G, s, t):
    """BFS bidireccional: expande por niveles completos el lado con la frontera más pequeña.

    Al generar v desde el lado A se comprueba si v ya está en los alcanzados del lado B. Como B solo ha
    completado niveles enteros, el primer encuentro ya es un camino mínimo.
    """
    if s == t:
        return 0, 0
    dist = [{s: 0}, {t: 0}]
    front = [[s], [t]]
    expandidos = 0
    while front[0] and front[1]:
        a = 0 if len(front[0]) <= len(front[1]) else 1
        nuevo = []
        for u in front[a]:
            expandidos += 1
            for v in G[u]:
                if v in dist[1 - a]:
                    return dist[a][u] + 1 + dist[1 - a][v], expandidos
                if v not in dist[a]:
                    dist[a][v] = dist[a][u] + 1
                    nuevo.append(v)
        front[a] = nuevo
    return None, expandidos

def geometrico(n, radio, semilla):
    """Grafo geométrico aleatorio en el cuadrado unidad (sin depender de scipy)."""
    pos = np.random.default_rng(semilla).random((n, 2))
    d2 = ((pos[:, None, :] - pos[None, :, :]) ** 2).sum(-1)
    i, j = np.nonzero(np.triu(d2 < radio**2, k=1))
    G = nx.Graph()
    G.add_nodes_from(range(n))
    G.add_edges_from(zip(i.tolist(), j.tolist()))
    return G

def comparar(G, nombre, pares, semilla=0):
    rng = np.random.default_rng(semilla)
    nodos = list(G)
    exp_u, exp_b, distancias, ok = [], [], [], 0
    for _ in range(pares):
        s, t = (nodos[k] for k in rng.choice(len(nodos), 2, replace=False))
        du, eu = bfs_uni(G, s, t)
        if du is None:
            continue
        db, eb = bfs_bi(G, s, t)
        ref = nx.shortest_path_length(G, s, t)
        camino = nx.bidirectional_shortest_path(G, s, t)
        ok += (du == db == ref == len(camino) - 1)
        exp_u.append(eu); exp_b.append(eb); distancias.append(ref)
    print(f"{nombre}: {len(exp_u)} pares, distancia media {np.mean(distancias):.1f}, "
          f"coinciden con networkx {ok}/{len(exp_u)}")
    print(f"   expandidos de media: unidireccional {np.mean(exp_u):.0f}, bidireccional {np.mean(exp_b):.0f}, "
          f"cociente de las medias {np.mean(exp_u) / np.mean(exp_b):.1f}")

geo = geometrico(1200, 0.065, 1)
comparar(geo, "geométrico aleatorio (n = 1200, r = 0.065)", 80)
reg = nx.random_regular_graph(3, 6000, seed=1)
comparar(reg, "3-regular aleatorio (n = 6000)", 80)

The distances match networkx for every pair, and the two graphs have similar average distances (10.2 and 10.8), but the saving is of a different order. In the geometric graph, bidirectional search expands 278 nodes on average versus 525: a factor of 1.9, the 2D−1=22^{D-1} = 2 of a two-dimensional space. In the 3-regular graph, 124 versus 2146: a factor of 17. There the number of nodes at distance kk grows like 2k2^k and bidirectional search replaces 2d2^{d} with 2⋅2d/22 \cdot 2^{d/2}. Incidentally, nx.bidirectional_shortest_path uses the same strategy as bfs_bi: it expands the side with fewer frontier nodes by levels and returns the first meeting.

The next cell reproduces the two-frontier interactive in Python: the same terrain, neighbor order and tie-breaking, with both stopping rules.

[ ]The stopping rule with costsBrowser
TERRENO = ["#~~#...~..~.~.~..",
           ".~....#.......~.#",
           ".~.....~~......~~",
           "~.~.~~~..~.~.....",
           "~~..~.~~..~~.~~~.",
           ".S..#...~......G.",
           ".~....~.~~~#...##",
           ".~...~.~~.#..~.#.",
           "~#........~#...#.",
           ".~~.~~....~....#.",
           ".#.~..~~.#....~~."]
celdas = {(r, c): ch for r, row in enumerate(TERRENO) for c, ch in enumerate(row)}
S = next(p for p, ch in celdas.items() if ch == "S")
G = next(p for p, ch in celdas.items() if ch == "G")
coste = lambda p: 5 if celdas[p] == "~" else 1          # entrar en p cuesta su terreno

def vecinos(p):
    r, c = p
    for q in ((r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)):
        if q in celdas and celdas[q] != "#":
            yield q

def ucs_bidireccional(regla):
    """Coste uniforme hacia delante desde S y hacia atrás desde G; expande el lado con la cima menor."""
    dist = [{S: 0}, {G: 0}]
    cerrado = [set(), set()]
    heaps = [[(0, 0, S)], [(0, 0, G)]]
    tie = itertools.count(1)
    mu, expansiones = float("inf"), 0

    def cima(lado):
        h = heaps[lado]
        while h and (h[0][2] in cerrado[lado] or h[0][0] > dist[lado][h[0][2]]):
            heapq.heappop(h)                              # entradas obsoletas
        return h[0][0] if h else float("inf")

    while True:
        tf, tb = cima(0), cima(1)
        if tf == float("inf") or tb == float("inf"):
            return mu, mu, expansiones
        if regla == "mu" and tf + tb >= mu:
            return mu, mu, expansiones
        lado = 0 if tf <= tb else 1
        g, _, u = heapq.heappop(heaps[lado])
        cerrado[lado].add(u)
        expansiones += 1
        if regla == "primer encuentro" and u in cerrado[1 - lado]:
            return dist[0][u] + dist[1][u], mu, expansiones
        for v in vecinos(u):
            # hacia atrás se recorre la arista real v -> u, que cuesta el terreno de u
            g2 = g + (coste(v) if lado == 0 else coste(u))
            if g2 < dist[lado].get(v, float("inf")):
                dist[lado][v] = g2
                heapq.heappush(heaps[lado], (g2, next(tie), v))
            if v in dist[1 - lado]:
                mu = min(mu, dist[lado][v] + dist[1 - lado][v])

rejilla = GridProblem([row.replace("S", ".").replace("G", ".") for row in TERRENO], S, G)
optimo, st_u = search(rejilla, "priority")
print("coste uniforme (un sentido):         coste", optimo.g, "  expandidos", st_u["expanded"])
for regla in ("primer encuentro", "mu"):
    c, mu, e = ucs_bidireccional(regla)
    print(f"bidireccional, regla {regla!r:<20} coste devuelto {c}   mu al parar {mu}   expansiones {e}")

The figures match the interactive: the first-meeting rule returns cost 24 after 154 expansions, the μ\mu rule returns the optimum, 20, after 117, and one-way uniform-cost needs 134. Notice two things. When the incorrect rule stops, μ\mu is already 20: the search saw the optimal path and returns another. It also works harder because the two searches continue to grow until one cell is closed by both, well after topF+topB\mathrm{top}_F + \mathrm{top}_B reaches μ\mu.

The library version

There is no standard Python library for “state-space search,” for good reason: the space is implicit and each problem defines its own successors. The aima-python repository accompanying Russell and Norvig’s book has educational implementations of all algorithms in this lesson. There are highly optimized explicit-graph libraries for spaces that fit in memory: networkx (pure Python, convenient) and scipy.sparse.csgraph (compiled, on sparse matrices).

[ ]The same maze with networkx and scipyBrowser
import networkx as nx
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra, breadth_first_order

# el laberinto de antes, ahora como grafo explícito: arista p -> q con el coste de entrar en q
D = nx.DiGraph()
for r in range(n):
    for c in range(n):
        if rows[r][c] == "#":
            continue
        for a in lab.actions((r, c)):
            q = lab.result((r, c), a)
            D.add_edge((r, c), q, weight=lab.action_cost((r, c), a, q))
s, t = lab.initial, lab.goal
print("networkx, pasos (anchura):           ", nx.shortest_path_length(D, s, t))
print("networkx, coste (Dijkstra):          ", nx.dijkstra_path_length(D, s, t))
coste_bi, camino_bi = nx.bidirectional_dijkstra(D, s, t)
print("networkx, coste (Dijkstra bidirecc.):", coste_bi, " pasos del camino:", len(camino_bi) - 1)

# scipy trabaja con matrices dispersas indexadas por enteros
idx = {v: k for k, v in enumerate(D.nodes)}
M = nx.to_scipy_sparse_array(D, nodelist=list(D.nodes), weight="weight", format="csr")
dist = dijkstra(csr_matrix(M), indices=idx[s])
print("scipy.sparse.csgraph.dijkstra:       ", dist[idx[t]])
orden = breadth_first_order(csr_matrix(M), idx[s], return_predecessors=False)
print("casillas alcanzables desde el inicio:", len(orden), "de", D.number_of_nodes())

The four calls confirm the custom engine: 78 steps in breadth-first, cost 120 with Dijkstra in one direction and in both, and the same 120 in scipy. The code for nx.bidirectional_dijkstra is worth reading: it alternates sides and stops as soon as a vertex leaves one side’s heap having already been settled by the other, the tempting rule, but returns not the path through that vertex but the best complete path seen when relaxing edges, μ\mu. This variant is also correct: when vertex vv leaves one side already settled by the other, that side’s top is its distance and the other side’s top is at least the distance of vv from that side, so topF+topB≥gF(v)+gB(v)≥μ\mathrm{top}_F + \mathrm{top}_B \ge g_F(v) + g_B(v) \ge \mu already holds and the theorem applies. It shows that what fails in the first-meeting rule is not the stopping time but which path is returned. The last line also explains the difference in philosophy: using these libraries requires materializing the whole graph (here 1258 cells, 1249 reachable), which for the 8-puzzle already means 181 440 nodes and for the 15-puzzle is impossible. The generic engine in this lesson generates on demand and is what you will extend through the module; its closest connection outside it is dynamic programming on Markov decision processes, which traverses the same state space but computes values instead of paths (value iteration).

Common mistakes

Exercises

QuizCosts 1 and 10
In a problem whose actions cost 1 or 10, which blind algorithms guarantee a minimum-cost solution (when one exists and bb is finite)? Select all that guarantee it.

More than one answer may be correct.

QuizOn generation or expansion?
You implement graph BFS and graph uniform-cost search. Where should each apply the goal test to preserve optimality with minimal work?
NumericIterative deepening nodes
In a uniform tree with b=3b = 3 and the solution at the last node of level d=8d = 8, how many nodes does iterative deepening generate, excluding the root?
NumericThe ratio, unrounded
With the same b=3b = 3 and d=8d = 8, what is the ratio NID/NBFSN_{\mathrm{ID}}/N_{\mathrm{BFS}}? Give four decimal places.
NumericHow deep uniform-cost search goes
In a problem with action costs c≥ε=0.25c \ge \varepsilon = 0.25 and optimal cost C∗=10C^* = 10, what is the greatest possible depth of a node generated by uniform-cost search before returning the solution?
NumericSavings from searching from both sides
In a uniform tree with b=10b = 10 and the solution at depth d=8d = 8, BFS generates ∑k=1810k\sum_{k=1}^{8} 10^k nodes and bidirectional search performs two searches to depth 4. How many times fewer nodes does bidirectional search generate?
QuizWhat to store in the reached table
Your engine stores 8-puzzle states as keys in a reached dictionary. Which representations are correct? Select all.

More than one answer may be correct.

QuizCan we search backward?
To which of these problems can bidirectional search be directly applied? Select all.

More than one answer may be correct.

ProofUniform-cost search is optimal
Prove: Consider a problem with finite bb and action costs c≥ε>0c \ge \varepsilon > 0. Graph uniform-cost search (reached table with gg updates and goal test on expansion) returns, if a solution exists, a solution of cost C∗C^*.
0
Let g∗(s)g^*(s) be the minimum cost of a path from s0s_0 to ss. A removal is valid if it does not correspond to a stale heap entry.

Step 1 of 4. Why are nodes removed (validly) in nondecreasing order of gg?

CodeIterative deepening with cycle checking
Implement iterative_deepening(problem, max_depth=100). The problem has problem.initial, problem.actions(s), problem.result(s, a) and problem.is_goal(s). Return the list of states on the shortest path (in number of actions) from the initial state to a goal, or None if none exists. Requirements: tree search without a reached table; do not repeat a state already on the current path; distinguish depth cutoff from absence of a solution, so that in a finite space without a solution you stop when an iteration cuts off no branches, without reaching max_depth.
def iterative_deepening(problem, max_depth=100):
  """Camino más corto (lista de estados) o None. Árbol con comprobación de ciclos en el camino."""
  # tu código: búsqueda limitada recursiva que distinga "corte" de "sin solución",
  # y el bucle de límites 0, 1, 2, ...
  return None
Shift+Enter to run

Summary

Key idea
Blind algorithms are one loop distinguished by two decisions: frontier order (queue, stack or cost heap) and whether reached states are remembered. From those decisions follow, with short proofs, completeness, optimality and cost in terms of bb, dd, mm and C∗/εC^*/\eps.
  • A search problem is defined by states, initial state, actions, transition model, goal test and costs; the state space is implicit and generated on demand. Its size is estimated with invariants (the 8-puzzle has 9!/2=181 4409!/2 = 181\,440 reachable states).
  • Tree search repeats states through cycles and transpositions; graph search eliminates them at the cost of memory proportional to reached states, which must be immutable and hashable.
  • BFS is complete and optimal with equal costs, with time and memory O(bd)\bigO(b^d); testing on generation is correct for it.
  • Uniform-cost is Dijkstra on an implicit graph with stopping at the goal: optimal with costs ≥ε>0\ge \eps > 0, testing on expansion and cost O(b1+⌊C∗/ε⌋)\bigO(b^{1 + \lfloor C^*/\eps \rfloor}).
  • DFS has linear memory and nothing else; iterative deepening recovers BFS completeness and optimality with O(bd)\bigO(bd) memory, and repeating levels costs exactly bb−1(NBFS−d)\frac{b}{b-1}(N_{\mathrm{BFS}} - d) nodes: less than a factor b/(b−1)b/(b-1).
  • Bidirectional search replaces bdb^d with 2bd/22b^{d/2} if there is an explicit goal and invertible actions, but only in exponentially growing spaces, and needs the correct stopping condition: complete levels without costs, topF+topB≥μ\mathrm{top}_F + \mathrm{top}_B \ge \mu with costs.