---
title: "Search and Games"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 28
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/28-search-and-games
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 28 — Search and Games

The sliding-tile puzzle has eight numbered tiles in a $3 \times 3$ frame and one empty cell; a move slides a tile into the empty cell, and the goal is to put the tiles in order. A program can try every sequence of moves, but how many it has to try depends on how it chooses:

```python
if __name__ == "__main__":
    rng = random.Random(3)
    print("moves  BFS expanded  A* misplaced  A* Manhattan")
    for walk in [10, 20, 40, 80, 3000]:
        start = scrambled(walk, rng)
        path, n_bfs = bfs(start, lambda s: s == GOAL, successors)
        _, c1, n_mis = astar(start, lambda s: s == GOAL, successors, misplaced)
        _, c2, n_man = astar(start, lambda s: s == GOAL, successors, manhattan)
        assert len(path) - 1 == c1 == c2
        print(f"{c1:5} {n_bfs:13} {n_mis:13} {n_man:13}")
```

***Listing 28.1.** Five scrambled puzzles solved three ways, counting the states each search expands code/bachelor-2/28-search-and-games/listings/eight_puzzle.py*

```
$ python eight_puzzle.py
moves  BFS expanded  A* misplaced  A* Manhattan
    8           226            21            14
   10           441            53            32
   16         13741           699           141
   20         44097          3501           772
   24        122340         18619          2392
```

***Output 28.1.** The same shortest solutions, found after very different amounts of work.*

All three searches return a shortest solution, and the third expands fifty times fewer states than the first on the hardest puzzle. The difference is an estimate of the distance left, used carefully enough that the answer stays optimal. The second half of the chapter adds an opponent: in noughts and crosses, or in a race between a robot and a rival through the town, each player chooses in turn, and a program can still compute who wins, and how.

**You already know.**

The Year 1 volume: breadth-first and depth-first search; Dijkstra’s algorithm for shortest paths with non-negative weights, and its proof; priority queues kept as binary heaps; backtracking. The grade 10 volume: graphs, paths and trees.

## 28.1 State spaces

**Definition 28.1 (State space, search problem, goal test).**

A *search problem* is given by a set of *states*, a start state, a *goal test* that says whether a state is a goal, and for each state its *successors*, each reached by an action of cost $c > 0$. The states and the actions form a directed graph, the *state space*; a solution is a path from the start to a goal, and an optimal solution one of least total cost.

The [state space](#def-b2-search-and-games-state-space) is usually never built: the 8-puzzle has $9!/2 = 181{,}440$ reachable states, chess far more than any memory holds. The program knows only the start and a function that lists successors; the graph is *implicit*, and a search builds the part it visits.

![Part of the 8-puzzle’s state space. The start has four successors, one per tile that can slide; each is labelled with its Manhattan distance h, the sum over the tiles of their distances to their places. The thick path is the solution of two moves; h points straight at it.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/fig-2bb5016d1d2a.svg)

*Part of the 8-puzzle’s [state space](#def-b2-search-and-games-state-space). The start has four successors, one per tile that can slide; each is labelled with its Manhattan distance $h$, the sum over the tiles of their distances to their places. The thick path is the solution of two moves; $h$ points straight at it.*

```python
def bfs(start, is_goal, successors):
    parent, queue, expanded = {start: None}, deque([start]), 0
    while queue:
        s = queue.popleft()
        expanded += 1
        if is_goal(s):
            return path_to(parent, s), expanded
        for t, _ in successors(s):
            if t not in parent:
                parent[t] = s
                queue.append(t)
    return None, expanded
```

***Listing 28.2.** Breadth-first search in an implicit graph, counting the states expanded code/bachelor-2/28-search-and-games/listings/state_space.py*

Breadth-first search expands the states in order of depth, so it finds a solution with fewest actions. If each state has at most $b$ successors and the shallowest goal is at depth $d$, it may expand $1 + b + \dots + b^d = O(b^d)$ states, and keeps them all in memory. Depth-first search keeps only the current path, but may go down forever, or find a long solution first.

**Definition 28.2 (Iterative deepening).**

*Iterative deepening* runs a depth-first search limited to depth $0$, then $1$, then $2$, and so on, until a limit at which it finds a goal.

It finds a solution with fewest actions, like breadth-first search, while keeping only a path of $d + 1$ states. Repeating the shallow levels costs little: with $b \geq 2$ the last level holds at least half of all the states up to it, and the total work is $O(b^d)$ again (Exercises [28.3](#exo-b2-search-and-games-3) and [28.4](#exo-b2-search-and-games-4)).

```python
def depth_limited(s, is_goal, successors, limit, path, count):
    count[0] += 1
    if is_goal(s):
        return list(path)
    if limit == 0:
        return None
    for t, _ in successors(s):
        if t not in path:  # no cycles along the current path
            path.append(t)
            found = depth_limited(t, is_goal, successors, limit - 1, path, count)
            path.pop()
            if found:
                return found
    return None


def iterative_deepening(start, is_goal, successors, max_depth=50):
    count = [0]
    for limit in range(max_depth + 1):
        found = depth_limited(start, is_goal, successors, limit, [start], count)
        if found:
            return found, count[0]
    return None, count[0]
```

***Listing 28.3.** Depth-limited search, which never revisits a state of the current path, and [iterative deepening](#def-b2-search-and-games-iddfs) code/bachelor-2/28-search-and-games/listings/state_space.py*

## 28.2 Uniform-cost search

When actions have different costs, as roads have different lengths, fewest actions is not cheapest.

**Definition 28.3 (Uniform-cost search).**

*Uniform-cost search* keeps a priority queue of states ordered by $g(s)$, the cost of the cheapest path to $s$ found so far. It repeatedly removes a state of smallest $g$, marks it *expanded*, stops if it is a goal, and otherwise updates $g$ for its successors not yet expanded.

It is Dijkstra’s algorithm of the Year 1 volume, run on an implicit graph and stopped at the first goal.

**Theorem 28.4 (Uniform-cost search).**

With positive action costs, [uniform-cost search](#def-b2-search-and-games-ucs) expands states in order of non-decreasing distance from the start; when it expands a state $s$, $g(s)$ is the distance to $s$. In particular the first goal expanded is reached by an optimal solution.

**Proof.** This is the invariant of Dijkstra’s algorithm, proved in the Year 1 volume: if a state $s$ were expanded with $g(s)$ larger than its distance, the first state $u$ of an optimal path to $s$ that is not yet expanded would have, from its expanded predecessor, $g(u)$ equal to its distance, at most the distance of $s$, which is less than $g(s)$, so $u$ would have been removed from the queue first. A goal expanded first is at the least distance among the goals: any closer goal would have been expanded before. ∎

## 28.3 Heuristics and A*

[Uniform-cost search](#def-b2-search-and-games-ucs) spreads in every direction. Most problems come with knowledge of the direction to go: the straight-line distance to the destination, or how far each tile is from its place.

**Definition 28.5 (Heuristic, admissible, consistent).**

A *heuristic* is a function $h \geq 0$ on states that estimates the cost of reaching a goal, with $h = 0$ on goals. Write $h^*(s)$ for the true least cost from $s$ to a goal. The heuristic is *admissible* if $h(s) \leq h^*(s)$ for every $s$: it never overestimates. It is *consistent* if $h(s) \leq c + h(t)$ for every action from $s$ to $t$ of cost $c$.

**Proposition 28.6 (Consistent implies admissible).**

A [consistent heuristic](#def-b2-search-and-games-heuristic) is [admissible](#def-b2-search-and-games-heuristic).

**Proof.** [Exercise 28.8](#exo-b2-search-and-games-8): follow an optimal path from $s$ to a goal and add the inequalities. ∎

**Method 28.7 (A*).**

[Uniform-cost search](#def-b2-search-and-games-ucs) in which the priority of a state $s$ is $f(s) = g(s) + h(s)$, the cost so far plus the estimate of the cost left.

```python
def astar(start, is_goal, successors, h=lambda s: 0, order=None):
    """A*: expand the state of smallest g + h. With h = 0, uniform-cost search.
    Returns (path, cost, number of states expanded); order lists them if given."""
    g, parent = {start: 0}, {start: None}
    frontier, done, tie = [(h(start), 0, start)], set(), 0
    while frontier:
        _, _, s = heapq.heappop(frontier)
        if s in done:
            continue  # a stale entry: s was reached again more cheaply
        done.add(s)
        if order is not None:
            order.append(s)
        if is_goal(s):
            return path_to(parent, s), g[s], len(done)
        for t, cost in successors(s):
            if t not in done and g[s] + cost < g.get(t, float("inf")):
                g[t], parent[t] = g[s] + cost, s
                tie += 1  # a counter breaks ties without comparing states
                heapq.heappush(frontier, (g[t] + h(t), tie, t))
    return None, float("inf"), len(done)
```

***Listing 28.4.** A*: [uniform-cost search](#def-b2-search-and-games-ucs) when $h = 0$ code/bachelor-2/28-search-and-games/listings/state_space.py*

**Theorem 28.8 (Optimality of A*).**

If $h$ is [consistent](#def-b2-search-and-games-heuristic), A* as in [Listing 28.4](#lst-b2-search-and-games-astar), which never expands a state twice, returns an optimal solution, and it expands the states in order of non-decreasing $f$.

**Proof.** Give each action from $s$ to $t$ the new cost $c' = c - h(s) + h(t)$, which is $\geq 0$ by consistency. Along any path from the start $s_0$ to a state $t$, the new costs add up to the old cost minus $h(s_0)$ plus $h(t)$: the middle terms cancel. So the new distance to $t$ is $g(t) - h(s_0) + h(t)$, the priority of A* minus a constant. A* is therefore [uniform-cost search](#def-b2-search-and-games-ucs) on the new costs, and by [Theorem 28.4](#thm-b2-search-and-games-ucs) (whose proof needs only non-negative costs) it expands states in order of new distance, that is of $f$, with $g$ exact. On goals $h = 0$, so the order of new distances among goals is that of true distances, and the first goal expanded is an optimal one. ∎

If $h$ is only [admissible](#def-b2-search-and-games-heuristic), A* that may expand a state again, when it finds a cheaper path to it, is still optimal; the listing, which never expands a state twice, may then return a longer path. A [heuristic](#def-b2-search-and-games-heuristic) that overestimates loses the guarantee altogether ([Exercise 28.2](#exo-b2-search-and-games-2)).

For the 8-puzzle, the number of misplaced tiles and the Manhattan distance are both [consistent](#def-b2-search-and-games-heuristic): one move changes one tile’s position by one cell, so it changes either [heuristic](#def-b2-search-and-games-heuristic) by at most $1$ ([Exercise 28.9](#exo-b2-search-and-games-9)). The Manhattan distance is never smaller than the number of misplaced tiles, and [Output 28.1](#out-b2-search-and-games-hook) shows what that buys: the closer $h$ is to $h^*$, the fewer states A* expands.

![The five puzzles of on a logarithmic scale. All three counts grow exponentially with the depth; a better heuristic lowers the rate of growth, not only the level.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/fig-3a87d6100fdb.svg)

*The five puzzles of [Output 28.1](#out-b2-search-and-games-hook) on a logarithmic scale. All three counts grow exponentially with the depth; a better [heuristic](#def-b2-search-and-games-heuristic) lowers the rate of growth, not only the level.*

On the town’s map, the straight-line distance between two places is [consistent](#def-b2-search-and-games-heuristic), by the triangle inequality, and no road is shorter than the straight line between its ends.

```
$ python town_astar.py
30 places; roads shorter than the straight line: 0
Bus Depot to Football Ground: 2430 m, straight line 2051 m; expanded 5 (Dijkstra) and 3 (A*)
   route: 16-4-15
Lighthouse Café to West Gate: 3860 m, straight line 2692 m; expanded 14 (Dijkstra) and 6 (A*)
   route: 30-25-17-22
Station to Old Mill: 4620 m, straight line 2365 m; expanded 29 (Dijkstra) and 10 (A*)
   route: 2-11-6-20-19-14
```

***Output 28.2.** Three routes on the town map: the same lengths, and a third to three fifths of the expansions.*

![The town’s places at their coordinates, from the Station (2) to the Old Mill (14). Uniform-cost search expands 29 places, shaded grey or coloured, spreading in every direction; A* expands only the 10 coloured ones, which lie towards the goal. The thick line is the route both return. Drawn by town_fig.py from the same search.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/fig-9b33f0d7d571.svg)

*The town’s places at their coordinates, from the Station (2) to the Old Mill (14). [Uniform-cost search](#def-b2-search-and-games-ucs) expands 29 places, shaded grey or coloured, spreading in every direction; A* expands only the 10 coloured ones, which lie towards the goal. The thick line is the route both return. Drawn by `town_fig.py` from the same search.*

**History.**

Peter Hart, Nils Nilsson and Bertram Raphael published A* in 1968, with the proof that an [admissible](#def-b2-search-and-games-heuristic) estimate keeps the answer optimal.

## 28.4 Two-player reachability games

![Two players at a café table. In a game like this one, each move is chosen by the player whose turn it is, and the question is no longer which path exists but which outcome a player can force.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/img-2dc14e1b0391.jpg)

*Two players at a café table. In a game like this one, each move is chosen by the player whose turn it is, and the question is no longer which path exists but which outcome a player can force.*

**Definition 28.9 (Reachability game, position, game graph).**

A *reachability game* is played by two players, $0$ and $1$, on a directed graph, the *game graph*, whose vertices, the *positions*, each belong to one player, with a set $T$ of target positions. A token starts on a position; the owner of the position where the token stands moves it along an edge. Player $p$ wins if the token reaches $T$; otherwise, including when the play goes on forever or stops at a position with no edge, player $p$ does not win.

**Definition 28.10 (Strategy, winning strategy, winning position).**

A *strategy* for player $p$ chooses a successor for each position of $p$ given the play so far; it is *memoryless* if the choice depends only on the current position. It is *winning* from a position if every play from there in which $p$ follows it reaches $T$, whatever the other player does; that position is then a *winning position* for $p$.

**Definition 28.11 (Attractor).**

The *attractor* of $T$ for player $p$ is built in layers: layer $0$ is $T$; a position not yet in it joins at layer $i + 1$ if it belongs to $p$ and has a successor in layer $i$ or before, or belongs to the other player and all its successors (at least one) are in layers $\leq i$. The attractor is the union of the layers.

```python
def attractor(owner, succ, target, p):
    """The positions from which p can force a visit to target, each with its layer
    (target is reached within that many moves), and a memoryless strategy for p."""
    pred = {v: [] for v in owner}
    for u in owner:
        for v in succ[u]:
            pred[v].append(u)
    left = {u: len(succ[u]) for u in owner}  # successors not yet in the attractor
    layer = {v: 0 for v in target}
    strategy, queue = {}, deque(target)
    while queue:
        v = queue.popleft()
        for u in pred[v]:
            if u in layer:
                continue
            if owner[u] == p:  # one good move is enough
                layer[u], strategy[u] = layer[v] + 1, v
                queue.append(u)
            else:
                left[u] -= 1
                if left[u] == 0:  # every move of the opponent leads in
                    layer[u] = layer[v] + 1
                    queue.append(u)
    return layer, strategy
```

***Listing 28.5.** The [attractor](#def-b2-search-and-games-attractor) computed backwards, with a counter of the successors left for each position of the opponent code/bachelor-2/28-search-and-games/listings/games.py*

**Theorem 28.12 (Attractor).**

The [attractor](#def-b2-search-and-games-attractor) of $T$ for player $p$ is exactly the set of [positions](#def-b2-search-and-games-game) from which $p$ has a [winning strategy](#def-b2-search-and-games-strategy). On it, the [memoryless strategy](#def-b2-search-and-games-strategy) that moves from each position of $p$ to a successor of a lower layer is [winning](#def-b2-search-and-games-strategy). The listing computes the [attractor](#def-b2-search-and-games-attractor) and this [strategy](#def-b2-search-and-games-strategy) in time $O(|V| + |E|)$.

**Proof.** From a position of layer $i > 0$, if it belongs to $p$, the [strategy](#def-b2-search-and-games-strategy) moves to a lower layer; if it belongs to the other player, every move leads to a lower layer. So the layer decreases at each move and the token reaches layer $0$, which is $T$, within $i$ moves.

Conversely, let $u$ be outside the [attractor](#def-b2-search-and-games-attractor). Then $u \notin T$. If $u$ belongs to $p$, all its successors are outside, since one inside would have put $u$ in. If $u$ belongs to the other player, it has a successor outside, or no successor at all, since otherwise $u$ would have joined. The other player can therefore always keep the token outside the [attractor](#def-b2-search-and-games-attractor): play never reaches $T$, whatever $p$ does, and $p$ has no [winning strategy](#def-b2-search-and-games-strategy) from $u$.

The listing processes each position once from the queue and looks at each edge once backwards, decrementing a counter; the running time is $O(|V| + |E|)$ ([Exercise 28.12](#exo-b2-search-and-games-12)). ∎

The theorem also says that memory is useless in [reachability games](#def-b2-search-and-games-game): if $p$ can win at all, $p$ can win by looking only at the current position. In the game of matches, 21 matches lie on the table, each player takes 1, 2 or 3 in turn, and whoever takes the last match wins. A position is the number left and the player to move.

```python
# 21 matches; a move takes 1, 2 or 3; whoever takes the last match wins. A position
# is (matches left, player to move); with no match left, the player to move has lost.
owner, succ = {}, {}
for k in range(22):
    for p in "AB":
        owner[(k, p)] = p
        other = "B" if p == "A" else "A"
        succ[(k, p)] = [(k - t, other) for t in (1, 2, 3) if t <= k]
win_a, strat = attractor(owner, succ, [(0, "B")], "A")
wins = [k for k in range(22) if (k, "A") in win_a]
print("A, to move, wins with k matches left for k =", " ".join(map(str, wins)))
print("A's winning move from 21:", f"take {21 - strat[(21, 'A')][0]};",
      "moves of both players until the end:", win_a[(21, "A")])
```

***Listing 28.6.** The game of matches as a [game graph](#def-b2-search-and-games-game); A wins on reaching “no match left, B to move” code/bachelor-2/28-search-and-games/listings/attractor.py*

```
$ python attractor.py
A, to move, wins with k matches left for k = 1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21
A's winning move from 21: take 1; moves of both players until the end: 11
player 0 forces e from [('a', 2), ('c', 1), ('e', 0)] strategy [('a', 'c'), ('c', 'e')]
player 1 forces h from [('b', 1), ('h', 0)]
neither: ['d', 'f', 'g']
```

***Output 28.3.** The [positions](#def-b2-search-and-games-game) won by the player to move, the first move from 21, and a small game in which some [positions](#def-b2-search-and-games-game) are won by neither.*

The player to move loses exactly with a multiple of 4: whatever they take, the other takes the complement to 4. From 21, take 1. In the small game of the output, each player has a target: player $0$ wants $e$, player $1$ wants $h$. Neither can force anything from $d$, $f$ and $g$: from $d$, player $1$ goes to $f$, and $f$ and $g$ send the token back and forth for ever. These [positions](#def-b2-search-and-games-game) are *draws*.

![The small game of : circles belong to player 0, squares to player 1. Blue: the attractor of e for player 0, with its layers and the strategy in thick arrows. Red: the attractor of h for player 1. From the white positions neither player can force a win.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/fig-c43844422787.svg)

*The small game of [Output 28.3](#out-b2-search-and-games-attractor): circles belong to player $0$, squares to player $1$. Blue: the [attractor](#def-b2-search-and-games-attractor) of $e$ for player $0$, with its layers and the [strategy](#def-b2-search-and-games-strategy) in thick arrows. Red: the [attractor](#def-b2-search-and-games-attractor) of $h$ for player $1$. From the white [positions](#def-b2-search-and-games-game) neither player can force a win.*

## 28.5 Minimax and alpha–beta

The [attractor](#def-b2-search-and-games-attractor) needs the whole [game graph](#def-b2-search-and-games-game). For a game whose [positions](#def-b2-search-and-games-game) are too many, a program looks a few moves ahead and estimates the rest.

**Definition 28.13 (Game tree, minimax value, evaluation function).**

In a game where two players alternate, max and min , the *game tree* of a position has that position at its root and the [positions](#def-b2-search-and-games-game) after each move as children. The leaves carry a value for max : the result of a finished game, or the value of an *evaluation function* at the depth where the search stops. The *minimax value* of a node is its leaf value, the largest value of its children if max is to move, and the smallest if min is.

The [minimax value](#def-b2-search-and-games-minimax) is what max can guarantee against any play of min , and min against any play of max , in the tree as given; the move to play is towards a child of the root with the root’s value.

**Definition 28.14 (Alpha–beta pruning).**

*Alpha–beta pruning* computes the [minimax value](#def-b2-search-and-games-minimax) with two bounds passed down the tree: $\alpha$, the value max is already sure of on the path from the root, and $\beta$, the value min is already sure of. As soon as a node’s value is known to be outside $(\alpha, \beta)$, its remaining children are skipped: the player above has a better choice elsewhere.

```python
def alphabeta(node, maximise, alpha, beta, count):
    """The minimax value if it lies strictly between alpha and beta; otherwise a bound
    on the same side as the true value."""
    if isinstance(node, int):
        count[0] += 1
        return node
    if maximise:
        value = -math.inf
        for c in node:
            value = max(value, alphabeta(c, False, alpha, beta, count))
            alpha = max(alpha, value)
            if alpha >= beta:
                break  # min above will never let play come here
        return value
    value = math.inf
    for c in node:
        value = min(value, alphabeta(c, True, alpha, beta, count))
        beta = min(beta, value)
        if alpha >= beta:
            break  # max above already has better
    return value
```

***Listing 28.7.** Alpha–beta, counting the leaves it evaluates code/bachelor-2/28-search-and-games/listings/alphabeta.py*

```
$ python minimax_demo.py
values of the min nodes: [5, 2, 2]
values of the max nodes below them: [[5, 9], [2, 7], [2, 8]]
value of the root: 5
alpha-beta value: 5 | leaves evaluated: 000 001 010 100 101 200 201 (7 of 12)
```

***Output 28.4.** A tree of depth 3 with three moves at the root and two below: its [minimax values](#def-b2-search-and-games-minimax), and the leaves that alpha–beta evaluates.*

![The tree of : triangles pointing up are nodes, down nodes. After the first subtree the root is sure of 5. In the second subtree, can already force 2 < 5 after two leaves, so its second child is never looked at; the same in the third. Dashed: the 5 leaves skipped. The bounds ≥ 6 and ≤ 2 are all alpha–beta knows of those nodes.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-search-and-games/fig-0f816efc539e.svg)

*The tree of [Output 28.4](#out-b2-search-and-games-demo): triangles pointing up are max nodes, down min nodes. After the first subtree the root is sure of $5$. In the second subtree, min can already force $2 < 5$ after two leaves, so its second child is never looked at; the same in the third. Dashed: the 5 leaves skipped. The bounds $\geq 6$ and $\leq 2$ are all alpha–beta knows of those nodes.*

**Theorem 28.15 (Alpha–beta).**

Let $v$ be the [minimax value](#def-b2-search-and-games-minimax) of a node and $r$ the result of alpha–beta on it with bounds $\alpha < \beta$. If $\alpha <
v < \beta$, then $r = v$; if $v \leq \alpha$, then $r \leq \alpha$; if $v \geq \beta$, then $r \geq \beta$. In particular, with $\alpha = -\infty$ and $\beta = +\infty$, alpha–beta returns the [minimax value](#def-b2-search-and-games-minimax).

**Proof.** [Exercise 28.10](#exo-b2-search-and-games-10), by induction on the height of the node. ∎

How much is skipped depends on the order of the children: if the best move comes first, its value sets the tightest bound at once.

**Proposition 28.16 (The best case).**

On a uniform tree of branching $b$ and depth $d$ whose children are always ordered best first, alpha–beta evaluates exactly $b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1$ of the $b^d$ leaves, when the leaf values are distinct.

**Proof.** *Admitted at this level.* ∎

A leaf is evaluated exactly when, along its path from the root, all the choices at the even depths are first children, or all the choices at the odd depths are; the first kind number $b^{\lfloor d/2 \rfloor}$, the second $b^{\lceil d/2
\rceil}$, and one leaf, the leftmost, is of both kinds. The characterisation is the analysis of Knuth and Moore.

```
$ python alphabeta.py
 b  d  leaves   alpha-beta, random order  best order  b^ceil(d/2)+b^floor(d/2)-1
 3  6     729                       155          53                           53
 4  6    4096                       917         127                          127
 4  8   65536                      7139         511                          511
 8  5   32768                      5752         575                          575
```

***Output 28.5.** Random uniform trees: all leaves, alpha–beta in random order, and alpha–beta with the children sorted best first.*

With perfect ordering the count is exactly the formula, about $2b^{d/2}$: in the same time, alpha–beta searches twice as deep as minimax. In random order it still skips most leaves. Real programs approach the best case by trying first the moves that were best in a shallower search.

**History.**

John von Neumann published the theory of games of [strategy](#def-b2-search-and-games-strategy), with the minimax theorem, in 1928. Donald Knuth and Ronald Moore published their analysis of [alpha–beta pruning](#def-b2-search-and-games-alpha-beta), with the best case above, in 1975.

## 28.6 Noughts and crosses, solved

Noughts and crosses is small enough to search completely. A position is a string of nine cells; $x$ moves first.

```python
@cache
def value(b):
    """The minimax value: x maximises, o minimises."""
    ms = moves(b)
    if not ms:
        return score(b)
    best = max if to_move(b) == "x" else min
    return best(value(m) for m in ms)


def count_tree(b):
    """Nodes and leaves of the full game tree below b."""
    ms = moves(b)
    if not ms:
        return 1, 1
    nodes, leaves = 1, 0
    for m in ms:
        n, f = count_tree(m)
        nodes, leaves = nodes + n, leaves + f
    return nodes, leaves
```

***Listing 28.8.** The value of a position by minimax with memoisation, and the size of the full [game tree](#def-b2-search-and-games-minimax) code/bachelor-2/28-search-and-games/listings/tictactoe.py*

```
$ python tictactoe.py
value of the empty board: 0
distinct positions reachable: 5478
game tree: 549946 nodes, 255168 finished games
x in the centre, then o in a corner: 0 | o on an edge: 1
```

***Output 28.6.** The game solved: a draw with best play.*

The full tree has 549,946 nodes, but only 5,478 distinct [positions](#def-b2-search-and-games-game): the same position is reached by many orders of the same moves, and the memo computes each once. The value $0$ says that neither player can force a win: the game is a draw if both play well. The last line shows a mistake that loses: after a cross in the centre, a nought on an edge lets the crosses force a win. With the eight symmetries of the square the [positions](#def-b2-search-and-games-game) drop to 765 ([Exercise 28.11](#exo-b2-search-and-games-11)).

## 28.7 Exercises

**Exercise 28.1 ★.**

Run breadth-first search on the town’s roads from the Bus Depot by hand, taking the neighbours of each place in the order of the road table, and list the places by depth. Check with `exo_bfs_order.py`.

**Solution of Exercise 28.1.**

The queue starts with the Bus Depot (16). Its roads lead to 4, 7 and 24, in that order, which form depth 1. Expanding 4 adds 15; 7 adds 23; 24 adds 1 and 3: depth 2. The process goes on until every place is reached, at depth 6 at most.

```
$ python exo_bfs_order.py
depth 0: [16]
depth 1: [4, 7, 24]
depth 2: [15, 23, 1, 3]
depth 3: [14, 19, 20, 10, 26]
depth 4: [5, 6, 13, 2, 9, 21]
depth 5: [11, 12, 17, 28, 18]
depth 6: [8, 30, 22, 25, 27, 29]
```

***Output 28.8.** The places by depth from the Bus Depot, in the order they leave the queue.*

**Exercise 28.2 ★.**

Use three times the straight-line distance as the [heuristic](#def-b2-search-and-games-heuristic) of A* on the town map. Find a pair of places for which the route returned is longer than the shortest one, and explain which step of the proof of [Theorem 28.8](#thm-b2-search-and-games-astar-optimal) fails. Check with `exo_inadmissible.py`.

**Solution of Exercise 28.2.**

From the Bus Depot to the Bakery Corner, A* with three times the straight line returns a route of 4,800 m, while the shortest is 4,360 m. On the other two pairs it is lucky, and it expands fewer states every time.

```
$ python exo_inadmissible.py
Station to Old Mill, h = 1 x straight line: 4620 m, 10 expanded, route 2-11-6-20-19-14
Station to Old Mill, h = 3 x straight line: 4620 m, 7 expanded, route 2-11-6-20-19-14
Lighthouse Café to West Gate, h = 1 x straight line: 3860 m, 6 expanded, route 30-25-17-22
Lighthouse Café to West Gate, h = 3 x straight line: 3860 m, 4 expanded, route 30-25-17-22
Bus Depot to Bakery Corner, h = 1 x straight line: 4360 m, 6 expanded, route 16-4-15-20-13
Bus Depot to Bakery Corner, h = 3 x straight line: 4800 m, 5 expanded, route 16-7-15-20-13
```

***Output 28.9.** An overestimate expands fewer states and can return a longer route.*

In the proof, the new cost $c' = c - h(s) + h(t)$ was non-negative because $h$ was [consistent](#def-b2-search-and-games-heuristic). With $h$ three times the straight line, a road of length $c$ towards the goal can lower $h$ by up to $3c$, so $c'$ can be negative, and the argument of [uniform-cost search](#def-b2-search-and-games-ucs), which needs non-negative costs, breaks. The [heuristic](#def-b2-search-and-games-heuristic) is not even [admissible](#def-b2-search-and-games-heuristic): at North School $h = 3 \times 2\,971 = 8\,914$ m against a true $3\,620$ m, so its priority, $740 + 8\,914 = 9\,654$ m, is above the Swimming Pool’s $1\,770 + 7\,717 = 9\,487$ m. The Swimming Pool is expanded first, the Football Ground is reached and closed through it with $g = 2\,870$ m instead of $2\,430$ m, 440 m too long, and the listing never reopens it.

**Exercise 28.3 ★.**

Compare [iterative deepening](#def-b2-search-and-games-iddfs) with breadth-first search on scrambled 8-puzzles: states expanded, and states kept in memory. Use `exo_iddfs.py`.

**Solution of Exercise 28.3.**

```
$ python exo_iddfs.py
depth  4: BFS expands    29, iterative deepening     53; IDDFS keeps a path of 5 states
depth 10: BFS expands   605, iterative deepening   1705; IDDFS keeps a path of 11 states
depth 20: BFS expands 37899, iterative deepening 280582; IDDFS keeps a path of 21 states
```

***Output 28.10.** [Iterative deepening](#def-b2-search-and-games-iddfs) expands more states, but keeps only one path.*

Breadth-first search keeps every state it has generated, tens of thousands at depth 20; [iterative deepening](#def-b2-search-and-games-iddfs) keeps a path of $d + 1$ states. It expands more than the ratio $b/(b - 1)$ of [Exercise 28.4](#exo-b2-search-and-games-4) suggests, seven times more at depth 20, because the 8-puzzle’s [state space](#def-b2-search-and-games-state-space) is a graph, not a tree: depth-first search reaches the same state by many paths and expands it each time, while breadth-first search expands it once. [Iterative deepening](#def-b2-search-and-games-iddfs) trades time for memory.

**Exercise 28.4 ★.**

A tree in which every node has $b \geq 2$ children has $(b^{d+1} - 1)/(b - 1)$ nodes down to depth $d$. Prove it, and deduce that [iterative deepening](#def-b2-search-and-games-iddfs) expands at most $b/(b - 1)$ times as many nodes as one depth-limited search to depth $d$, counting nodes with repetition.

**Solution of Exercise 28.4.**

There are $b^k$ nodes at depth $k$, so $1 + b + \dots + b^d = (b^{d+1} - 1)/(b - 1)$ down to depth $d$, by the sum of a geometric series. [Iterative deepening](#def-b2-search-and-games-iddfs) runs the searches to depths $0, \dots, d$, so it expands

$$
\sum_{k=0}^{d} \frac{b^{k+1} - 1}{b - 1} \leq \frac{1}{b - 1} \sum_{k=0}^{d} b^{k+1} = \frac{b}{b - 1} \cdot \frac{b^{d+1}
- 1}{b - 1}
$$

nodes, which is $b/(b - 1)$ times the count of the last search alone: at most twice for $b = 2$, about $1.1$ times for $b = 10$.

**Exercise 28.5 ★★.**

Compute the [minimax value](#def-b2-search-and-games-minimax) of the tree `[[[4, 8, 2], [7, 1]], [[3], [9, 6], [5, 0]], [[6, 2], [1, 3, 8]]]` with min to move at the root, and then with max . Check with `exo_minimax.py`.

**Solution of Exercise 28.5.**

With min at the root, the second level is max and the third min . The children are

$$
\max(\min(4, 8, 2), \min(7, 1)) = \max(2, 1) = 2, \quad \max(3, 6, 0) = 6, \quad \max(2, 1) = 2,
$$

and the root is $\min(2, 6, 2) = 2$. With max at the root, the children are $\min(8, 7) = 7$, $\min(3, 9, 5) = 3$ and $\min(6, 8) = 6$, and the root is $7$.

```
$ python exo_minimax.py
min at the root: 2 | max at the root: 7
```

***Output 28.11.** The two values.*

**Exercise 28.6 ★★.**

The function `ab_short` of `exo_ab_bug.py` starts every node with $\alpha = -\infty$ and $\beta = +\infty$ instead of receiving them from its parent. Is its value right? How many leaves does it evaluate, and why?

**Solution of Exercise 28.6.**

```
$ python exo_ab_bug.py
minimax     : value 297, 729 leaves
alpha-beta  : value 297, 321 leaves
fresh bounds: value 297, 729 leaves
```

***Output 28.12.** Without inherited bounds, nothing is pruned.*

The value is right, but all 729 leaves are evaluated. In a max node with fresh bounds, $\beta$ stays $+\infty$, so $\alpha \geq \beta$ never holds; in a min node, $\alpha$ stays $-\infty$. The function is minimax with a test that never fires. A cut-off happens when a node’s value falls outside a bound set by an ancestor: the bounds must come from above.

**Exercise 28.7 ★★.**

In the subtraction game, a move takes 1, 3 or 4 matches, and whoever takes the last wins. Compute the [attractor](#def-b2-search-and-games-attractor) for the first player from up to 30 matches, guess the losing [positions](#def-b2-search-and-games-game), and prove your guess.

**Solution of Exercise 28.7.**

```
$ python exo_subtraction.py
the player to move loses with k = [0, 2, 7, 9, 14, 16, 21, 23, 28, 30]
k mod 7 of these: [0, 2]
```

***Output 28.13.** The losing [positions](#def-b2-search-and-games-game) up to 30.*

Claim: the player to move loses exactly when $k \equiv 0$ or $2 \pmod 7$. By strong induction on $k$. With $k \equiv 0$, the moves lead to residues $6$, $4$ and $3$; with $k \equiv 2$, to $1$, $6$ and $5$: never to a losing residue, so by induction the opponent wins. From the other residues there is a move to a losing one: from $1$ take 1, from $3$ take 1, from $4$ take 4, from $5$ take 3, from $6$ take 4; in each case the move is possible, since $k$ is at least that residue. So these [positions](#def-b2-search-and-games-game) are won.

**Exercise 28.8 ★★.**

Prove [Proposition 28.6](#prop-b2-search-and-games-consistent-admissible).

**Solution of Exercise 28.8.**

Let $s = s_0, s_1, \dots, s_n$ be an optimal path to a goal $s_n$, with costs $c_1, \dots, c_n$. Consistency gives $h(s_{i-1}) \leq c_i + h(s_i)$ for each $i$. Adding these inequalities, the terms $h(s_1), \dots, h(s_{n-1})$ cancel and $h(s) \leq c_1 + \dots + c_n + h(s_n) = h^*(s)$, since $h = 0$ on goals. If no goal is reachable, $h^*(s) = \infty$ and there is nothing to prove.

**Exercise 28.9 ★★.**

Prove that the Manhattan distance of the 8-puzzle is [consistent](#def-b2-search-and-games-heuristic), and that it is never smaller than the number of misplaced tiles. Then compute the true distance of all 181,440 states by one breadth-first search backwards from the goal, and check both [heuristics](#def-b2-search-and-games-heuristic) against it.

**Solution of Exercise 28.9.**

A move slides one tile by one cell, so it changes that tile’s distance to its place by exactly $1$ and leaves the others unchanged: the Manhattan distance changes by $\pm 1$ for a move of cost $1$, hence $h(s) \leq 1 + h(t)$. Each misplaced tile is at least one cell from its place, so the Manhattan distance is at least the number of misplaced tiles. By [Proposition 28.6](#prop-b2-search-and-games-consistent-admissible) both are [admissible](#def-b2-search-and-games-heuristic).

```
$ python exo_manhattan.py
181440 states reachable; largest distance 31
misplaced: above the true distance 0 times, equal 79 times; mean gap 14.86
manhattan: above the true distance 0 times, equal 2351 times; mean gap 7.97
```

***Output 28.14.** Both [heuristics](#def-b2-search-and-games-heuristic) against the true distances of all reachable states.*

Neither [heuristic](#def-b2-search-and-games-heuristic) ever exceeds the true distance. The Manhattan distance is exact on 2,351 states and falls short by about 8 moves on average, against about 15 for the misplaced tiles: that gap is what [Output 28.1](#out-b2-search-and-games-hook) measures.

**Exercise 28.10 ★★★.**

Prove [Theorem 28.15](#thm-b2-search-and-games-alpha-beta).

**Solution of Exercise 28.10.**

Write $[x] = \min(\max(x, \alpha), \beta)$ for $x$ clamped to $[\alpha, \beta]$. The three cases of the theorem say exactly $[r] = [v]$: if $\alpha < v < \beta$, then $[r] = v$ forces $r = v$; if $v \leq \alpha$, $[r] = \alpha$ means $r \leq
\alpha$; if $v \geq \beta$, $[r] = \beta$ means $r \geq \beta$.

Induction on the height. At a leaf, $r = v$. Take a max node with children of values $v_1, \dots, v_k$, and let $m_j = \max(v_1, \dots, v_j)$ and $\mu_j$ the variable `value` after child $j$, with $m_0 = \mu_0 = -\infty$. We show $[\mu_j] = [m_j]$ for each $j$ that the loop reaches. It holds for $j = 0$. Suppose it holds for $j - 1$ and the loop goes on, so $\mu_{j-1} < \beta$. Then $m_{j-1} < \beta$ too, and both clamps equal $\alpha_j = \max(\alpha,
\mu_{j-1}) = \max(\alpha, m_{j-1})$, which is the lower bound passed to child $j$. For any $m < \beta$ and any $x$, a check of the three cases for $x$ (below $\alpha_m$, between $\alpha_m$ and $\beta$, above $\beta$) gives $[\max(m, x)] = \min(\max(x, \alpha_m), \beta)$ with $\alpha_m = \max(\alpha,
m)$. Applying it with $m = \mu_{j-1}$, $x = r_j$, and with $m = m_{j-1}$, $x = v_j$, and using the induction hypothesis on child $j$ with bounds $(\alpha_j, \beta)$, gives $[\mu_j] = [m_j]$.

If the loop stops after child $j$ because $\mu_j \geq \beta$, then $[m_j] = [\mu_j] = \beta$, so $m_j \geq \beta$ and $v = m_k \geq m_j \geq \beta$: $[v] = \beta = [\mu_j]$. Otherwise the loop ends at $j = k$ with $[\mu_k] = [m_k] = [v]$. min nodes are symmetric, exchanging the roles of $\alpha$ and $\beta$ and of $\max$ and $\min$.

**Exercise 28.11 ★★★.**

Count the [positions](#def-b2-search-and-games-game) of noughts and crosses reachable from the empty board, then count them up to the rotations and reflections of the square, keeping one representative of each class.

**Solution of Exercise 28.11.**

```
$ python exo_symmetry.py
positions reachable: 5478; up to symmetry: 765
```

***Output 28.15.** The [positions](#def-b2-search-and-games-game), and their classes under the eight symmetries.*

A depth-first walk from the empty board collects the 5,478 reachable [positions](#def-b2-search-and-games-game). For each, the program computes its eight images under the four rotations and their mirror images, and keeps the smallest string as the representative of its class: two [positions](#def-b2-search-and-games-game) are in the same class exactly when they have the same representative. There are 765 classes. A search with memoisation keyed on the representative computes each value once per class.

**Exercise 28.12 ★★★.**

Prove that [Listing 28.5](#lst-b2-search-and-games-attractor) runs in time $O(|V| + |E|)$, and that a position of the opponent enters the [attractor](#def-b2-search-and-games-attractor) exactly when its counter reaches $0$.

**Solution of Exercise 28.12.**

Building the predecessor lists costs $O(|V| + |E|)$. A position is put in the queue only when it receives a layer, and never again, since [positions](#def-b2-search-and-games-game) with a layer are skipped; so each position leaves the queue at most once, and when $v$ leaves it, its predecessor list is walked once. Each edge $(u, v)$ is therefore looked at once, at constant cost: the loop costs $O(|V| + |E|)$ in all.

The counter of a position $u$ of the opponent starts at its number of successors, counted with repetition. It is decremented once for each edge $(u, v)$ when $v$ leaves the queue, that is once for each successor entering the [attractor](#def-b2-search-and-games-attractor). It reaches $0$ exactly when all successors are in the [attractor](#def-b2-search-and-games-attractor), which is the condition of the definition; with a counter instead of a check of all successors, the time stays linear.

## 28.8 Problem: The delivery robot and its rival

**Problem 28.1.**

Weekend problem — The delivery robot and its rival

A delivery robot leaves the Bus Depot with parcels for the Library (place 3), the Museum (12) and the Hospital (8), in any order. Then a rival robot tries to catch it on its way to the Library. Last, the robots play noughts and crosses.

```python
# Part I-II: start at the Bus Depot, deliver to the Library, the Museum and the
# Hospital in any order. A state is (place, deliveries still to make).
DEPOT, STOPS = 16, frozenset({3, 12, 8})


def successors(state):
    place, todo = state
    for nxt, d in ROADS.get(place, []):
        yield (nxt, todo - {nxt}), d


def h(state):  # the farthest stop left, in a straight line: admissible
    place, todo = state
    return max((straight(place, s) for s in todo), default=0)


start = (DEPOT, STOPS)
for name, heur in [("uniform cost", lambda s: 0), ("A*, farthest stop", h)]:
    path, cost, expanded = astar(start, lambda s: not s[1], successors, heur)
    print(f"{name:17}: {cost} m, {expanded} states expanded;",
          "route", "-".join(str(p) for p, _ in path))
```

***Listing 28.9.** The deliveries as a [search problem](#def-b2-search-and-games-state-space): a state is a place and the deliveries left code/bachelor-2/28-search-and-games/listings/robot_problem.py*

```
$ python robot_problem.py
uniform cost     : 11980 m, 114 states expanded; route 16-24-3-24-16-4-15-20-6-12-8
A*, farthest stop: 11980 m, 56 states expanded; route 16-24-3-24-16-4-15-20-6-12-8
1800 positions: robot wins from 784, rival from 202, neither from 814
robot at Bus Depot, rival at Station: robot wins, first move to South Bridge, 3 moves in all
robot at Bus Depot, rival at Town Square: neither wins
robot at Allotments, rival at Town Hall: rival wins after 8 moves in all
noughts and crosses: alpha-beta value 0 after 7330 finished games of 255168
```

***Output 28.7.** The best delivery round, the race game solved, and alpha–beta on noughts and crosses.*

**Part I — The state space.**

1. How many states does the delivery problem have? Which are goals?
2. Why must the state contain the deliveries left, and not only the place?
3. Why does the route of [Output 28.7](#out-b2-search-and-games-problem) go through the South Bridge twice? Is that allowed in the [state space](#def-b2-search-and-games-state-space) ?
4. How many actions does a state have, and what do they cost?
5. Would breadth-first search find the same route? Run it, and say why the answer is luck.
6. With $k$ stops instead of 3, how does the number of states grow?

**Part II — A* on the town.**

7. Prove that $h$ , the straight-line distance to the farthest stop left, is [admissible](#def-b2-search-and-games-heuristic) .
8. Prove that it is [consistent](#def-b2-search-and-games-heuristic) .
9. Would the sum of the straight-line distances to the stops left be [admissible](#def-b2-search-and-games-heuristic) ? Give a counterexample or a proof.
10. A* expands 56 states and [uniform-cost search](#def-b2-search-and-games-ucs) 114. Explain where the saving comes from.
11. Propose a better [admissible heuristic](#def-b2-search-and-games-heuristic) , and say why it is [admissible](#def-b2-search-and-games-heuristic) .
12. How would A* change if the robot had to return to the depot at the end?

**Part III — The race, solved backwards.**

13. [Positions](#def-b2-search-and-games-game) are (robot’s place, rival’s place, player to move). Check that there are 1,800.
14. Which [positions](#def-b2-search-and-games-game) form the robot’s target, and which the rival’s? Why do they get a loop?
15. From the Bus Depot, with the rival at the Station, the robot wins in 3 moves. Describe the play.
16. From the Bus Depot with the rival at the Town Square, neither wins. What do the robots do for ever?
17. From the Allotments, with the rival at the Town Hall, the rival wins. Why can it never be a draw there?
18. The robot wins from 784 [positions](#def-b2-search-and-games-game) and the rival from 202. Why is the game not symmetric?

**Part IV — Alpha–beta measured.**

19. On the random tree with $b = 4$ and $d = 8$ , compare the leaves evaluated in random order and best first with $4^8$ and with the formula of [Proposition 28.16](#prop-b2-search-and-games-best-case) .
20. In the same time, how much deeper does alpha–beta with perfect ordering search than minimax?
21. On noughts and crosses, alpha–beta finishes 7,330 of the 255,168 games. Why is the saving larger than on the random trees?
22. Why does alpha–beta call the game with $\alpha = -2$ and $\beta = 2$ rather than infinite bounds?
23. How should a program order the moves of noughts and crosses to approach the best case?
24. State the problem’s result: alpha–beta with good ordering visits $L$ of $N$ leaves, near the $b^{d/2}$ bound, with the values of $L$ and $N$ measured here.

**Solution of Problem 28.1.**

**1.** A state is a place and a subset of the three stops: $30 \times 2^3 = 240$ states. The goals are the 30 states with no delivery left.

**2.** The same place means different things before and after a delivery: the round from the Library back past the South Bridge would be a cycle if the state were the place alone, and the [goal test](#def-b2-search-and-games-state-space), “all parcels delivered”, could not be read from it.

**3.** Only two roads leave the Library, to the South Bridge and to the Garden Centre, and the shortest way on to the Museum goes back over the South Bridge. The states $(24, \{3, 8, 12\})$ and $(24, \{8, 12\})$ are different, so the route is a simple path in the [state space](#def-b2-search-and-games-state-space).

**4.** One action per road leaving the place, with one-way roads only in their direction; its cost is the road’s length. The deliveries left lose the new place if it is a stop.

**5.** Here it does: breadth-first search on the same [state space](#def-b2-search-and-games-state-space) returns the same round, 10 roads and 11 980 m. That is luck: breadth-first search minimises the number of roads, not the metres, and on another map the round of fewest roads may be longer.

**6.** $30 \cdot 2^k$: exponential in the number of stops, as for the travelling salesman problem.

**7.** Any route that delivers the stops left visits the farthest one, $s$, so its length is at least the road distance to $s$, which is at least the straight line, since no road is shorter than the straight line between its ends. On goals $h = 0$.

**8.** Take an action from $(u, S)$ to $(v, S')$ along a road of length $d \geq \lVert u - v \rVert$. For $s \in S$: if $s = v$, then $\lVert u - s \rVert \leq d$; otherwise $s \in S'$ and $\lVert u - s \rVert \leq d + \lVert v - s \rVert \leq d
+ h(v, S')$. Taking the maximum over $s$, $h(u, S) \leq d + h(v, S')$.

**9.** No. With stops 1 km and 2 km away along a straight road, the round costs 2 km and the sum is 3 km.

**10.** A* never expands a state with $g + h$ above 11,980 m, the optimal cost; [uniform-cost search](#def-b2-search-and-games-ucs) expands every state with $g$ below it, including those that head away from the remaining stops.

**11.** The length of a minimum spanning tree, in straight lines, of the current place and the stops left. Any round from the place through all the stops, shortened to straight lines between the points it visits in order, is a spanning path, so at least as long as the minimum spanning tree: the [heuristic](#def-b2-search-and-games-heuristic) is [admissible](#def-b2-search-and-games-heuristic). It is at least the old $h$, since the tree contains a path to the farthest stop.

**12.** The goal becomes $(16, \varnothing)$, and a natural [admissible heuristic](#def-b2-search-and-games-heuristic) is the maximum over the stops left of the straight line to the stop plus the straight line from it to the depot, or the straight line to the depot when no stop is left.

**13.** The robot has 30 places, the rival 30, and the turn two values: $30 \cdot 30 \cdot 2 = 1{,}800$.

**14.** The robot’s target is the [positions](#def-b2-search-and-games-game) with the robot at the Library and the rival elsewhere; the rival’s, those with both robots on the same place. The play stops there, and the loop gives each such position a successor, so that the definition of the [attractor](#def-b2-search-and-games-attractor), which asks about all successors, applies everywhere.

**15.** The robot moves to the South Bridge. The rival, at the Station, can reach only the Town Hall, the River Park and the Hill Park, none of which is the South Bridge or the Library. The robot then moves to the Library: three moves in all.

**16.** On foot every road is two-way, so the Library has three neighbours: the South Bridge, the Garden Centre and the Town Square itself. A rival at the Town Square is next to the Library and to both other places next to it, so it answers any step of the robot onto one of the three by a capture, and the robot keeps away. The position is in neither [attractor](#def-b2-search-and-games-attractor): by the proof of [Theorem 28.12](#thm-b2-search-and-games-attractor), the rival can keep the token out of the robot’s [attractor](#def-b2-search-and-games-attractor) and the robot can keep it out of the rival’s, so the robots circle for ever, the rival guarding the Library and the robot keeping out of reach.

**17.** The position is in the rival’s [attractor](#def-b2-search-and-games-attractor), at layer 8: by [Theorem 28.12](#thm-b2-search-and-games-attractor) the rival has a [strategy](#def-b2-search-and-games-strategy) that catches the robot within 8 moves, whatever the robot does. A position in an [attractor](#def-b2-search-and-games-attractor) is won, so it is never a draw.

**18.** The targets differ: the robot must reach one fixed place, the rival must meet a moving robot. Moreover the robot is caught whenever the two share a place, whoever moved last.

**19.** Of the $4^8 = 65{,}536$ leaves, alpha–beta evaluates 7,139 in random order, about 11 %, and 511 when the children are best first, exactly $4^4 + 4^4 - 1$.

**20.** The best case is about $2b^{d/2}$ leaves. In the time minimax takes to search to depth $d$, about $b^d$ leaves, alpha–beta searches to about $2d$: twice as deep.

**21.** The values are only $-1$, $0$ and $1$, and most are draws: as soon as a player is sure of $0$ and the other finds $0$, the test $\alpha \geq \beta$ holds and the rest is cut. Many games also end before the board is full, so the tree is far from uniform.

**22.** All values lie in $[-1, 1]$, so $-2$ and $2$ act as infinite bounds: by [Theorem 28.15](#thm-b2-search-and-games-alpha-beta) the value returned is exact, and the program stays in integers.

**23.** Try first a move that wins at once, then one that blocks the opponent’s line, then the centre, the corners and the edges; or the moves that were best in a shallower search, or best according to the memo.

**24.** On the random tree with $b = 4$ and $d = 8$, alpha–beta with perfect ordering visits $L = 511$ of $N =
65{,}536$ leaves, exactly the bound $b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1$; on noughts and crosses, it finishes 7,330 of the 255,168 games.
