এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
28Search and Games
The sliding-tile puzzle has eight numbered tiles in a 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:
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}")
$ 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
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 . 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 is usually never built: the 8-puzzle has 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.
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
Breadth-first search expands the states in order of depth, so it finds a solution with fewest actions. If each state has at most successors and the shallowest goal is at depth , it may expand 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 , then , then , 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 states. Repeating the shallow levels costs little: with the last level holds at least half of all the states up to it, and the total work is again (Exercises 28.3 and 28.4).
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]
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 , the cost of the cheapest path to found so far. It repeatedly removes a state of smallest , marks it expanded, stops if it is a goal, and otherwise updates 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 expands states in order of non-decreasing distance from the start; when it expands a state , is the distance to . 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 were expanded with larger than its distance, the first state of an optimal path to that is not yet expanded would have, from its expanded predecessor, equal to its distance, at most the distance of , which is less than , so 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 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 on states that estimates the cost of reaching a goal, with on goals. Write for the true least cost from to a goal. The heuristic is admissible if for every : it never overestimates. It is consistent if for every action from to of cost .
Proposition 28.6 (Consistent implies admissible)
Proof. Exercise 28.8: follow an optimal path from to a goal and add the inequalities. ∎
Method 28.7 (A*)
Uniform-cost search in which the priority of a state is , the cost so far plus the estimate of the cost left.
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)
Theorem 28.8 (Optimality of A*)
If is consistent, A* as in Listing 28.4, which never expands a state twice, returns an optimal solution, and it expands the states in order of non-decreasing .
Proof. Give each action from to the new cost , which is by consistency. Along any path from the start to a state , the new costs add up to the old cost minus plus : the middle terms cancel. So the new distance to is , the priority of A* minus a constant. A* is therefore uniform-cost search on the new costs, and by Theorem 28.4 (whose proof needs only non-negative costs) it expands states in order of new distance, that is of , with exact. On goals , so the order of new distances among goals is that of true distances, and the first goal expanded is an optimal one. ∎
If is only admissible, 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 that overestimates loses the guarantee altogether (Exercise 28.2).
For the 8-puzzle, the number of misplaced tiles and the Manhattan distance are both consistent: one move changes one tile’s position by one cell, so it changes either heuristic by at most (Exercise 28.9). The Manhattan distance is never smaller than the number of misplaced tiles, and Output 28.1 shows what that buys: the closer is to , the fewer states A* expands.
On the town’s map, the straight-line distance between two places is consistent, 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
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 estimate keeps the answer optimal.
28.4 Two-player reachability games
Definition 28.9 (Reachability game, position, game graph)
A reachability game is played by two players, and , on a directed graph, the game graph, whose vertices, the positions, each belong to one player, with a set of target positions. A token starts on a position; the owner of the position where the token stands moves it along an edge. Player wins if the token reaches ; otherwise, including when the play goes on forever or stops at a position with no edge, player does not win.
Definition 28.10 (Strategy, winning strategy, winning position)
A strategy for player chooses a successor for each position of 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 follows it reaches , whatever the other player does; that position is then a winning position for .
Definition 28.11 (Attractor)
The attractor of for player is built in layers: layer is ; a position not yet in it joins at layer if it belongs to and has a successor in layer or before, or belongs to the other player and all its successors (at least one) are in layers . The attractor is the union of the layers.
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
Theorem 28.12 (Attractor)
The attractor of for player is exactly the set of positions from which has a winning strategy. On it, the memoryless strategy that moves from each position of to a successor of a lower layer is winning. The listing computes the attractor and this strategy in time .
Proof. From a position of layer , if it belongs to , the 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 , which is , within moves.
Conversely, let be outside the attractor. Then . If belongs to , all its successors are outside, since one inside would have put in. If belongs to the other player, it has a successor outside, or no successor at all, since otherwise would have joined. The other player can therefore always keep the token outside the attractor: play never reaches , whatever does, and has no winning strategy from .
The listing processes each position once from the queue and looks at each edge once backwards, decrementing a counter; the running time is (Exercise 28.12). ∎
The theorem also says that memory is useless in reachability games: if can win at all, 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.
# 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")])
$ 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']
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 wants , player wants . Neither can force anything from , and : from , player goes to , and and send the token back and forth for ever. These positions are draws.
28.5 Minimax and alpha–beta
The attractor needs the whole game graph. For a game whose positions 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 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 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 with two bounds passed down the tree: , the value max is already sure of on the path from the root, and , the value min is already sure of. As soon as a node’s value is known to be outside , its remaining children are skipped: the player above has a better choice elsewhere.
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
$ 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)
Theorem 28.15 (Alpha–beta)
Let be the minimax value of a node and the result of alpha–beta on it with bounds . If , then ; if , then ; if , then . In particular, with and , alpha–beta returns the minimax value.
Proof. Exercise 28.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 and depth whose children are always ordered best first, alpha–beta evaluates exactly of the 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 , the second , 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
With perfect ordering the count is exactly the formula, about : 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, with the minimax theorem, in 1928. Donald Knuth and Ronald Moore published their analysis of alpha–beta pruning, 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; moves first.
@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
$ 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
The full tree has 549,946 nodes, but only 5,478 distinct positions: the same position is reached by many orders of the same moves, and the memo computes each once. The value 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 drop to 765 (Exercise 28.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
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]
Exercise 28.2 ★
Use three times the straight-line distance as the 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 fails. Check with exo_inadmissible.py.
Solution
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
In the proof, the new cost was non-negative because was consistent. With three times the straight line, a road of length towards the goal can lower by up to , so can be negative, and the argument of uniform-cost search, which needs non-negative costs, breaks. The heuristic is not even admissible: at North School m against a true m, so its priority, m, is above the Swimming Pool’s m. The Swimming Pool is expanded first, the Football Ground is reached and closed through it with m instead of m, 440 m too long, and the listing never reopens it.
Exercise 28.3 ★
Compare iterative deepening with breadth-first search on scrambled 8-puzzles: states expanded, and states kept in memory. Use exo_iddfs.py.
Solution
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
Breadth-first search keeps every state it has generated, tens of thousands at depth 20; iterative deepening keeps a path of states. It expands more than the ratio of Exercise 28.4 suggests, seven times more at depth 20, because the 8-puzzle’s 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 trades time for memory.
Exercise 28.4 ★
A tree in which every node has children has nodes down to depth . Prove it, and deduce that iterative deepening expands at most times as many nodes as one depth-limited search to depth , counting nodes with repetition.
Solution
Solution of Exercise 28.4.
There are nodes at depth , so down to depth , by the sum of a geometric series. Iterative deepening runs the searches to depths , so it expands
nodes, which is times the count of the last search alone: at most twice for , about times for .
Exercise 28.5 ★★
Compute the minimax value 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
Solution of Exercise 28.5.
With min at the root, the second level is max and the third min. The children are
and the root is . With max at the root, the children are , and , and the root is .
$ python exo_minimax.py
min at the root: 2 | max at the root: 7
Exercise 28.6 ★★
The function ab_short of exo_ab_bug.py starts every node with and instead of receiving them from its parent. Is its value right? How many leaves does it evaluate, and why?
Solution
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
The value is right, but all 729 leaves are evaluated. In a max node with fresh bounds, stays , so never holds; in a min node, stays . 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 for the first player from up to 30 matches, guess the losing positions, and prove your guess.
Solution
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]
Claim: the player to move loses exactly when or . By strong induction on . With , the moves lead to residues , and ; with , to , and : never to a losing residue, so by induction the opponent wins. From the other residues there is a move to a losing one: from take 1, from take 1, from take 4, from take 3, from take 4; in each case the move is possible, since is at least that residue. So these positions are won.
Exercise 28.8 ★★
Prove Proposition 28.6.
Solution
Solution of Exercise 28.8.
Let be an optimal path to a goal , with costs . Consistency gives for each . Adding these inequalities, the terms cancel and , since on goals. If no goal is reachable, and there is nothing to prove.
Exercise 28.9 ★★
Prove that the Manhattan distance of the 8-puzzle is consistent, 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 against it.
Solution
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 and leaves the others unchanged: the Manhattan distance changes by for a move of cost , hence . 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 both are admissible.
$ 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
Neither 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 measures.
Exercise 28.10 ★★★
Prove Theorem 28.15.
Solution
Solution of Exercise 28.10.
Write for clamped to . The three cases of the theorem say exactly : if , then forces ; if , means ; if , means .
Induction on the height. At a leaf, . Take a max node with children of values , and let and the variable value after child , with . We show for each that the loop reaches. It holds for . Suppose it holds for and the loop goes on, so . Then too, and both clamps equal , which is the lower bound passed to child . For any and any , a check of the three cases for (below , between and , above ) gives with . Applying it with , , and with , , and using the induction hypothesis on child with bounds , gives .
If the loop stops after child because , then , so and : . Otherwise the loop ends at with . min nodes are symmetric, exchanging the roles of and and of and .
Exercise 28.11 ★★★
Count the positions 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
Solution of Exercise 28.11.
$ python exo_symmetry.py
positions reachable: 5478; up to symmetry: 765
A depth-first walk from the empty board collects the 5,478 reachable positions. 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 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 runs in time , and that a position of the opponent enters the attractor exactly when its counter reaches .
Solution
Solution of Exercise 28.12.
Building the predecessor lists costs . A position is put in the queue only when it receives a layer, and never again, since positions with a layer are skipped; so each position leaves the queue at most once, and when leaves it, its predecessor list is walked once. Each edge is therefore looked at once, at constant cost: the loop costs in all.
The counter of a position of the opponent starts at its number of successors, counted with repetition. It is decremented once for each edge when leaves the queue, that is once for each successor entering the attractor. It reaches exactly when all successors are in the 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.
# 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))
$ 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
Part I — The state space.
- How many states does the delivery problem have? Which are goals?
- Why must the state contain the deliveries left, and not only the place?
- Why does the route of Output 28.7 go through the South Bridge twice? Is that allowed in the state space?
- How many actions does a state have, and what do they cost?
- Would breadth-first search find the same route? Run it, and say why the answer is luck.
- With stops instead of 3, how does the number of states grow?
Part II — A* on the town.
- Prove that , the straight-line distance to the farthest stop left, is admissible.
- Prove that it is consistent.
- Would the sum of the straight-line distances to the stops left be admissible? Give a counterexample or a proof.
- A* expands 56 states and uniform-cost search 114. Explain where the saving comes from.
- Propose a better admissible heuristic, and say why it is admissible.
- How would A* change if the robot had to return to the depot at the end?
Part III — The race, solved backwards.
- Positions are (robot’s place, rival’s place, player to move). Check that there are 1,800.
- Which positions form the robot’s target, and which the rival’s? Why do they get a loop?
- From the Bus Depot, with the rival at the Station, the robot wins in 3 moves. Describe the play.
- From the Bus Depot with the rival at the Town Square, neither wins. What do the robots do for ever?
- From the Allotments, with the rival at the Town Hall, the rival wins. Why can it never be a draw there?
- The robot wins from 784 positions and the rival from 202. Why is the game not symmetric?
Part IV — Alpha–beta measured.
- On the random tree with and , compare the leaves evaluated in random order and best first with and with the formula of Proposition 28.16.
- In the same time, how much deeper does alpha–beta with perfect ordering search than minimax?
- On noughts and crosses, alpha–beta finishes 7,330 of the 255,168 games. Why is the saving larger than on the random trees?
- Why does alpha–beta call the game with and rather than infinite bounds?
- How should a program order the moves of noughts and crosses to approach the best case?
- State the problem’s result: alpha–beta with good ordering visits of leaves, near the bound, with the values of and measured here.
Solution
Solution of Problem 28.1.
1. A state is a place and a subset of the three stops: 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, “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 and are different, so the route is a simple path in the 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 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. : exponential in the number of stops, as for the travelling salesman problem.
7. Any route that delivers the stops left visits the farthest one, , so its length is at least the road distance to , which is at least the straight line, since no road is shorter than the straight line between its ends. On goals .
8. Take an action from to along a road of length . For : if , then ; otherwise and . Taking the maximum over , .
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 above 11,980 m, the optimal cost; uniform-cost search expands every state with 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 is admissible. It is at least the old , since the tree contains a path to the farthest stop.
12. The goal becomes , and a natural admissible 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: .
14. The robot’s target is the positions 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, 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: by the proof of Theorem 28.12, the rival can keep the token out of the robot’s 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, at layer 8: by Theorem 28.12 the rival has a strategy that catches the robot within 8 moves, whatever the robot does. A position in an 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 leaves, alpha–beta evaluates 7,139 in random order, about 11 %, and 511 when the children are best first, exactly .
20. The best case is about leaves. In the time minimax takes to search to depth , about leaves, alpha–beta searches to about : twice as deep.
21. The values are only , and , and most are draws: as soon as a player is sure of and the other finds , the test 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 , so and act as infinite bounds: by Theorem 28.15 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 and , alpha–beta with perfect ordering visits of leaves, exactly the bound ; on noughts and crosses, it finishes 7,330 of the 255,168 games.