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
Why search
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.
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 and edges , which can be astronomical or infinite, but four local parameters:
- , the branching factor: the maximum number of successors of a state;
- , the depth of the shallowest solution: the smallest number of actions in a solution;
- , the maximum depth of any path in the space (possibly );
- and : the optimal cost and a positive lower bound on action costs, .
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 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 and the mean number of actions per blank position is .
There are 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 , or . 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.
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 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 and ; final saturation is what asymptotic analysis ignores and what makes everything work in small spaces. Scale jumps are brutal: the 15-puzzle has reachable states and Rubik’s cube has . 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 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:
- Put the initial state’s node in the frontier.
- While the frontier is not empty, remove a node according to the frontier policy.
- 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 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 even if there are only a handful of distinct states.
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 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 nodes, 380 times the states in the space, and the full tree has .
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 and the number of distinct states at distance .
- 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 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.
Breadth-first and uniform-cost search
Proof
By induction on : when the first node at depth is removed, the frontier contains only nodes at depths and , and every state at distance from the start has already been reached by a node at depth exactly . This is the FIFO queue invariant; the inductive step follows because the children of nodes at depth are exactly the states at distance 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 , a path’s cost is times its length, and minimum length is minimum cost. As level has at most nodes and the search goes no deeper than level , at most nodes are generated; all stay in the reached table, so memory is of the same order.
∎The cost is memory. With and , BFS stores on the order of 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 . The complexity bound has a short proof worth seeing, because it explains why the exponent is not .
Proof
UCS stops when it expands a goal, and the first it expands has . Since nodes leave in nondecreasing order of , every expanded node has . A node at depth has , so expanded nodes have depth , that is, , and generated nodes at most one more. The number of nodes at depth is . The same bound gives completeness: before expanding a goal, only the finitely many nodes with 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, and the bound is : one level more than BFS because the test is on expansion. But if actions costing coexist with actions costing 1, UCS explores sequences of cheap irrelevant actions in full detail before taking an expensive step toward the goal: with and , the exponent is 1001. And the assumption cannot be weakened to “positive costs”: with costs 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 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 costing 10, and and costing 1. Expanding generates with and with ; testing on generation returns at cost 10, although 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 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 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 , which can be much worse than or infinite. But its memory is linear: in a tree it stores only the current path and each path node’s pending siblings, nodes, or with backtracking. The graph version loses this advantage because the reached table grows as in BFS.
Depth-limited search cuts branches at depth : it treats nodes at depth as if they had no children. It always terminates, using memory and time, but fails if and is not optimal if . 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 regenerates everything generated by . The second, after doing the arithmetic, is that it does not matter.
Proof
The iteration with limit generates the complete tree to depth , that is, nodes; summing, level is generated in iterations , that is, times, giving the second expression. For the third, use the geometric series :
Dividing by gives , which is less than and tends to it because 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 times the last. With , IDDFS generates at most 11% more than BFS; with , twice as much. If BFS tests on expansion and generates level , IDDFS (which does not generate children of nodes at the limit) is even cheaper than BFS: the ratio tends to , so it wins for every , and with and generates 89% less. The bad case is : in a corridor each iteration costs as much as the previous one and the total is quadratic, , as you saw in the acyclic maze.
Completeness and optimality are inherited from BFS: the iteration with limit finds a solution if and only if one exists at depth , and iterations increase one by one, so the first solution appears in iteration and has depth . Time follows from the previous theorem; memory is that of depth-limited search with . 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.
Bidirectional search
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: instead of . With and , that is nodes versus .
The saving is spectacular, but has three conditions:
- 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.
- 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.
- 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 : it has reached exactly the states at distance from (plus those at distance that it is generating), and the backward side, which expands only complete levels, has reached exactly the states at distance from the goal . Since there was no earlier meeting, no state at distance from is at distance from , and therefore . If is now generated at distance from and was reached backward at distance , the path found has length . Combined with the lower bound, its length is exactly .
∎The complete-level assumption is not decorative: if we alternate node by node, the backward side may have reached some states of level and the first meeting may give a path one step longer than optimal. With costs, the problem is worse.
Proof
Always , because it is the cost of a real path. Suppose at stopping and take an optimal path . By the UCS invariant, every state at distance less than from has been expanded forward with its exact distance, and likewise backward with . For every on the optimal path, , so or . Let be the last on the path with (it exists because satisfies except in the trivial case). If , the goal is expanded forward with its exact distance and . Otherwise, has and is expanded backward with its exact distance. When the latter of the two was expanded, edge was relaxed with both distances already exact, and fell to at most . 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.
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 : on a grid the number of cells at distance grows like , not , and two disks of radius occupy half the area of one of radius . In general, in a space with polynomial growth of degree , bidirectional search saves a factor ; 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
| Algorithm | Complete? | Optimal? | Time | Memory |
|---|---|---|---|---|
| Breadth-first (BFS) | yes ⁽ᵃ⁾ | yes ⁽ᶜ⁾ | ||
| Uniform-cost | yes ⁽ᵃ ᵇ⁾ | yes | ||
| Depth-first (tree) | no ⁽ᵈ⁾ | no | ||
| Depth-limited | no | no | ||
| Iterative deepening | yes ⁽ᵃ⁾ | yes ⁽ᶜ⁾ | ||
| Bidirectional | yes ⁽ᵃ ᵉ⁾ | yes ⁽ᶜ ᵉ⁾ |
(a) if is finite; (b) if costs are ; (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 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.
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 , 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.
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 per level, and . 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.
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 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 , the worst case for both searches.
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 , and , as predicted by factor .
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 ), 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 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 pairs suffices.
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 of a two-dimensional space. In the 3-regular graph, 124 versus 2146: a factor of 17. There the number of nodes at distance grows like and bidirectional search replaces with . 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.
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 rule returns the optimum, 20, after 117, and one-way uniform-cost needs 134. Notice two things. When the incorrect rule stops, 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 reaches .
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).
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, . This variant is also correct: when vertex 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 from that side, so 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
More than one answer may be correct.
reached dictionary. Which representations are correct? Select all.More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. Why are nodes removed (validly) in nondecreasing order of ?
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 NoneSummary
- 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 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 ; testing on generation is correct for it.
- Uniform-cost is Dijkstra on an implicit graph with stopping at the goal: optimal with costs , testing on expansion and cost .
- DFS has linear memory and nothing else; iterative deepening recovers BFS completeness and optimality with memory, and repeating levels costs exactly nodes: less than a factor .
- Bidirectional search replaces with 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, with costs.