Hill Climbing on 8-Queens and the 8-Puzzle

The first CSC 742 assignment taken from demonstration to reproducible experiment, with the submitted programs replayed beside the rerun. Steepest-descent hill climbing solves 14% of random 8-queens boards and 94% with sideways moves, matching Russell and Norvig, while on the 8-puzzle it almost always stalls, and an exhaustive count of all 181,440 puzzle states shows why.

On 8-queens, steepest-descent hill climbing solves 14.0% of 30,000 seeded random boards, as Russell and Norvig (2020) report. Up to 100 sideways moves raise that to 94.3% with random tie-breaking but only to 32.5% with a fixed tie order, which loops. Random restarts without sideways moves solved every trial, in about 7 runs and 23 steps on average. Of the failed runs, 98.6% stop on a plateau and 95% within two attacking pairs of a solution. On the 8-puzzle it solves 1 in 1,000 uniform random instances under misplaced tiles ($h_1$) or Manhattan distance ($h_2$). Counting all 181,440 states shows why: 77% of moves leave $h_1$ unchanged, 24% of states are local minima of $h_2$, and strict descent can succeed only where the heuristic equals the true distance.

Two puzzles that look alike behave very differently under hill climbing. On the 8-queens problem, a steepest-descent hill climber started from a random board solves about one instance in seven. A few random restarts or a budget of sideways moves raise that to nearly every instance. On the 8-puzzle, the same algorithm with the textbook heuristic stops before reaching the goal on 999 of 1,000 random instances. Neither sideways moves nor a better heuristic changes the picture much. Why does the same algorithm succeed on one puzzle and fail on the other? On 8-queens, almost all failed runs stop on a plateau, 95% of them within two attacking pairs of a solution, and any solution will do. On the 8-puzzle, one heuristic is mostly flat and the other has local minima in a quarter of its states, and the answer wanted is a path from a fixed start.

The difference says more about the problems than about the algorithm, and it is a compact lesson in when local search is the right tool. The first assignment of CSC 742 asked for exactly this comparison:

  • hill climbing on the 8-puzzle, with the number of misplaced tiles as the heuristic;
  • hill climbing on 8-queens, with the number of attacking pairs;
  • a report of runs that succeed and runs that get stuck, and an explanation of how random restarts help.

The submitted solution was a pair of short Python programs and a report that ran a handful of unseeded instances and drew the board after every move. This article takes the assignment from demonstration to measured experiment. It reruns the same algorithms with seeds over thousands of boards and compares them with the figures that Russell and Norvig (2020) publish for 8-queens. It also adds an exhaustive analysis of the 8-puzzle, and it sets the submission's reported success rates, 20% on 8-queens and 33% on the 8-puzzle, beside the rerun.

First we define both problems and work one board and one climb by hand. Then we run the experiment on 8-queens, compare it with the book, and see why the rule for breaking ties matters so much. Next we run the 8-puzzle and count all of its states to see why hill climbing fails there. Then we replay the submitted programs and explain why their success rates differ from the rerun's. After that we answer the assignment in one place, with a traced run that succeeds and one that stops for each puzzle. Finally we draw the lessons. The general algorithm is described in hill climbing, and the remedies used here, sideways moves and restarts, in escaping local optima.

The two problems

8-queens. Place eight queens on a chessboard so that no two attack each other along a row, a column, or a diagonal. Russell and Norvig (2020, §4.1.1) use a complete-state formulation: every state has all eight queens on the board, one in each column. So a state is a list of eight row numbers, and there are $8^8 = 16{,}777{,}216$ states.

The heuristic $h$ counts the pairs of queens that attack each other, directly or through another queen in between. If $k$ queens share a row or a diagonal, they contribute $\binom{k}{2}$ pairs, so

$$h = \sum_{\ell} \binom{k_\ell}{2}.$$

The sum runs over the 8 rows and the 30 diagonals of both directions, and $k_\ell$ is the number of queens on line $\ell$. A solution has $h = 0$. A move takes one queen to another square in its own column, so every state has $8 \times 7 = 56$ neighbors.

A worked board

The board below is the state $(6, 0, 4, 3, 2, 1, 0, 2)$. The queen in column 0 is on row 6, the queen in column 1 on row 0, and so on, with row 0 at the bottom. It was chosen as the first seeded random board with $h = 17$, the same value as a well-known textbook example (Russell and Norvig, 2020, §4.1.1), though the board itself is different. Only three lines hold more than one queen:

Line Queens (by column) $k$ Pairs $\binom{k}{2}$
Diagonal with row + column = 6 0, 2, 3, 4, 5, 6 6 15
Row 0 1, 6 2 1
Row 2 4, 7 2 1
Total 17

The diagonal shows why $h$ counts indirect attacks. Six queens on one diagonal block one another, so only five pairs are adjacent along it, but the definition counts all $\binom{6}{2} = 15$ pairs. With that count, moving any one queen off a line that holds $k$ queens lowers $h$ by exactly $k - 1$, whichever queen it is, since $\binom{k}{2} - \binom{k-1}{2} = k - 1$. That makes the effect of a move easy to compute.

(a) The example board, with the lines along which queens attack: six queens on one diagonal give 15 pairs, and two pairs share rows 0 and 2, for h = 17. (b) The value of h after each of the 56 possible moves, written on the square the queen would move to. Look for the two boxed squares, row 7 in columns 4 and 6: they give the lowest value, 11, so steepest descent picks one of them at random.
(a) The example board, with the lines along which queens attack: six queens on one diagonal give 15 pairs, and two pairs share rows 0 and 2, for h = 17. (b) The value of h after each of the 56 possible moves, written on the square the queen would move to. Look for the two boxed squares, row 7 in columns 4 and 6: they give the lowest value, 11, so steepest descent picks one of them at random.

Each number in panel (b) can be checked the same way. Moving the queen of column 6 from row 0 to row 7 takes it off the long diagonal, where it was in conflict with five queens. It also leaves row 0, where it was in conflict with one. On its new square, row 7 is empty, and neither diagonal through the square in row 7, column 6 holds another queen. So it gains no conflicts, and $h = 17 - 5 - 1 = 11$. Moving the queen of column 4 to row 7 removes its five diagonal conflicts and its one conflict on row 2. Its new square, in row 7 and column 4, shares no row or diagonal with another queen either, so this move also gives $17 - 5 - 1 = 11$. These are the only two moves that reach 11. The 56 neighbors average 14.43, and some, such as moving the column-1 queen to row 5, make the board worse (22).

Steepest descent from this board, breaking ties with a seeded random choice, runs as follows:

Step $h$ Best neighbor $h$ Moves tied for best Move made
0 17 11 2 column 6, row 0 to 7
1 11 7 4 column 2, row 4 to 5
2 7 4 4 column 4, row 2 to 6
3 4 1 1 column 0, row 6 to 4
4 1 1 2 none: no neighbor is better
Steepest descent from the example board, one board per step, with the attacking lines drawn. The solid box marks the square a queen has just moved to and the dotted box the square it left; the label under each board gives the next move. Notice how quickly the climb falls, from 17 to 11, 7, 4 and 1, and then stops: no single move reaches 0.
Steepest descent from the example board, one board per step, with the attacking lines drawn. The solid box marks the square a queen has just moved to and the dotted box the square it left; the label under each board gives the next move. Notice how quickly the climb falls, from 17 to 11, 7, 4 and 1, and then stops: no single move reaches 0.

The climb is typical in two ways.

  • It is short, four moves, because each move removes several conflicts at once.
  • It stops at $h = 1$ with two neighbors that also have $h = 1$. This is a plateau, not a strict local minimum, so a hill climber allowed sideways moves would keep going.

A strict local minimum looks like the next board. One pair of queens attacks along a diagonal, and every one of the 56 moves leaves at least two attacking pairs:

A strict local minimum with h = 1: the queens in columns 3 and 6 share a diagonal. Every empty square shows h after the move there. Notice that none is below 2, so neither steepest descent nor sideways moves can make progress from this board.
A strict local minimum with h = 1: the queens in columns 3 and 6 share a diagonal. Every empty square shows h after the move there. Notice that none is below 2, so neither steepest descent nor sideways moves can make progress from this board.

The 8-puzzle. Eight numbered tiles and a blank sit on a 3 by 3 grid. A move slides a tile adjacent to the blank into it. The goal used here has the blank in the top-left corner and the tiles 1 to 8 in reading order. Two standard heuristics estimate the distance to the goal (Russell and Norvig, 2020, §3.6):

  • $h_1$, the number of misplaced tiles (the blank is not counted);
  • $h_2$, the sum over tiles of the Manhattan distance from each tile to its goal square.

Both are admissible: they never overestimate the number of moves still needed. Every misplaced tile must move at least once, and every tile must travel at least its Manhattan distance, one square per move.

Not every arrangement of the tiles can reach the goal. Johnson and Story (1879) settled the question for the 15-puzzle. Johnson showed that half of the arrangements are unreachable, and Story showed that the other half can all be reached. The same parity argument works on the 3 by 3 board.

Here is the idea in one sentence: some quantity that every move preserves must differ between an unreachable arrangement and the goal. Read the tiles in row order, ignoring the blank, and count inversions, pairs of tiles that appear in the wrong order.

  • A horizontal move does not change the reading order.
  • A vertical move carries one tile past the two tiles between its old and new positions in the reading order. Its order relative to each of those two tiles is reversed, and nothing else changes. Each reversal adds or removes one inversion, so the count changes by $-2$, $0$, or $+2$.

The parity of the inversion count never changes. The goal has no inversions, so only arrangements with an even count can be reached. Exactly half of the $9!$ arrangements have an even count. Exchanging tiles 1 and 2, wherever they sit, changes the count by exactly one: the pair itself is reversed, and every other tile is larger than both, so its order relative to the pair is unaffected. The exchange therefore matches each even arrangement with an odd one.

So at most $9!/2 = 181{,}440$ arrangements are reachable. The parity argument does not show that all of them are. A breadth-first search from the goal in the experiment below visits exactly 181,440 states, which confirms it. (Symmetric groups makes the same kind of parity argument for permutations in general, including the 15 puzzle.)

Example (tiles 1 and 2 exchanged). The goal with tiles 1 and 2 exchanged, and everything else in place, cannot be reached from the goal. In reading order its tiles are 2, 1, 3, 4, 5, 6, 7, 8, which has exactly one inversion. One is odd and the goal's count, zero, is even, so no sequence of moves connects them.

With both problems defined, the question is how often a hill climber solves them from random starts.

The experiment

The script tools/experiments/evolution/hill_climbing_puzzles.py in the site repository implements everything below in standard-library Python. Its hill climber is steepest descent: at each step it scores every neighbor and moves to one with the lowest heuristic value.

  • Without sideways moves, it stops as soon as the best neighbor is not strictly better than the current state.
  • With sideways moves, it may also move to a best neighbor of equal value, up to 100 consecutive times. The counter resets after each strict improvement, as in Russell and Norvig's version.

A step is one move. A run succeeds when the heuristic reaches 0.

When several neighbors tie for best, the book's pseudocode moves to one of them without saying which. The script implements two rules:

  • random tie-breaking picks uniformly among the best neighbors, with a seeded generator;
  • first tie-breaking takes the first best neighbor in a fixed order (column 0 to 7, then row 0 to 7).

The 8-queens results below show that the choice matters a great deal once sideways moves are allowed. The worked boards and puzzle states in this article come from a companion script, tools/experiments/evolution/puzzles_examples.py, which reuses the same functions. So do the extra tallies of where runs stop.

8-queens results

Each configuration ran from 30,000 random boards, in 30 seeded batches of 1,000.

Configuration Solved Mean steps when solved Mean steps when stuck
No sideways moves, random ties 14.02% 4.09 3.05
No sideways moves, first ties 14.68% 4.05 3.07
Up to 100 sideways moves, random ties 94.28% 19.16 60.68
Up to 100 sideways moves, first ties 32.45% 5.19 100.68
Russell and Norvig, no sideways moves about 14% 4 3
Russell and Norvig, 100 sideways moves about 94% 21 64

Across the 30 batches, the success rate without sideways moves had a median of 14.15% (interquartile range 13.0% to 14.7%). With sideways moves and random ties, the median was 94.25% (93.7% to 94.8%). The pooled 95% confidence intervals are 13.6% to 14.4% and 94.0% to 94.5%.

Agreement with the book. Russell and Norvig (2020, §4.1.1) report two sets of figures:

  • steepest-ascent hill climbing gets stuck 86% of the time, taking about 4 steps when it succeeds and 3 when it gets stuck;
  • allowing up to 100 consecutive sideways moves raises the success rate to about 94%, at a cost of about 21 steps per success and 64 per failure.

The success rates and the step counts without sideways moves reproduce. With sideways moves, the reproduction takes 19.16 steps on success and 60.68 on failure, with standard errors of 0.11 and 1.20. So the gaps to 21 and 64 are larger than sampling error in this experiment. The book does not state how many boards it used or exactly what it counted as a step. Its pseudocode does not fix a tie-breaking rule either. So the cause of the gap cannot be pinned down from the text. What the experiment does show is that the sideways-move figure depends heavily on the tie-breaking rule, which the pseudocode leaves open.

Why tie-breaking matters. Without sideways moves, the rule barely matters: 14.02% against 14.68%, in runs only three or four steps long. With sideways moves, the rule decides the outcome, 94.28% against 32.45%.

Example (a loop under first tie-breaking). Under first tie-breaking, the failed runs with sideways moves were going around in a loop. They average 100.68 steps, just over the budget of 100 sideways moves, which is the mark of a run that spent its whole budget. Under first tie-breaking the chosen move is a function of the state alone. So once a stretch of sideways moves returns to a state it has visited, it repeats the same loop until the budget of 100 is spent. That happened in 65.63% of all runs, which accounts for almost every failure (67.55% of runs failed). Random tie-breaking also revisits states, in 57.91% of runs, but it does not repeat the same loop. The walk keeps exploring the plateau, and only 3.20% of runs ended with the sideways budget exhausted. A sideways move is useful only as part of a random walk across a plateau. Deterministic sideways moves on a plateau are a cycle.

How close the failures come. Replaying the 30,000 runs without sideways moves (random ties) and recording $h$ where each run stopped shows that the failures are near misses:

Final $h$ Runs Share of the failed runs
0 (solved) 4,207
1 14,659 56.83%
2 9,967 38.64%
3 1,148 4.45%
4 19 0.07%

More than half of the failed runs stop one attacking pair away from a solution, and 95% stop within two. And almost none of them is a strict local minimum like the board pictured above. Of the 25,793 failed runs, 25,428 (98.6%) stopped at a board with at least one neighbor of equal $h$, as the worked descent did. Only 365 stopped at a board where every move makes $h$ worse.

This is why sideways moves are so effective here. Nearly every failure is a plateau, and a random walk across it often reaches a board from which $h$ can fall again. (The success count, 4,207 of 30,000, is the 14.02% of the table.)

Steepest descent on 8-queens. Every empty square shows the h the board would have if the queen of that column moved there, and the best squares are boxed. Step makes one steepest-descent move (random among ties); Run continues until the search stops. The example board starts at h = 17 with two best moves at 11. Turn on sideways moves and notice that the search now walks across plateaus instead of stopping; or click any square to move a queen by hand and watch the numbers change.

Random restarts

Random-restart hill climbing runs the hill climber from fresh random boards until one run succeeds. If each run succeeds independently with probability $p$, the number of runs needed is geometric with mean $1/p$; escaping local optima derives this. Russell and Norvig (2020, §4.1.1) add an expected step count: one successful run plus, on average, $(1 - p)/p$ failed ones,

$$E[\text{steps}] = s_{\text{ok}} + \frac{1 - p}{p}\, s_{\text{fail}}.$$

Here $s_{\text{ok}}$ and $s_{\text{fail}}$ are the mean step counts of successful and failed runs. With their figures this gives about 22 steps without sideways moves and about 25 with them. The script ran 10,000 restart trials for each setting, with random ties.

Setting Runs per solution, $1/p$ Runs, measured Steps, formula Steps, measured
No sideways moves 7.13 7.16 (median 5, IQR 2 to 10, max 53) 22.81 22.89 (median 16)
Up to 100 sideways moves 1.06 1.06 (median 1, max 5) 22.85 23.00 (median 12)

Restarts solved every trial. The geometric model fits closely, as it should, since the runs are independent. The measured restart figure with sideways moves, 23 steps rather than 25, follows from the lower per-run step counts above.

The two strategies cost the same number of steps on average. Sideways moves spend their steps walking across plateaus; restarts spend them on short runs that end in local minima. Each step evaluates the same 56 neighbors either way.

The mean hides a long tail. Without sideways moves, the median trial needed 5 runs, but one needed 53. The probability of having a solution within $k$ runs is $1 - (1 - p)^k$: about 53% after 5 runs, 78% after 10, and 90% only after 16. Escaping local optima checks that formula against these trials run by run.

For larger boards, the representation matters more than these tricks. Sosič and Gu (1990) placed one queen in each row and each column from the start, as a permutation, so that only diagonal conflicts remain. They then swapped pairs of queens whenever a swap reduced the number of conflicts. A linear-time extension of that algorithm (Sosič and Gu, 1991) solved the 3,000,000-queens problem in about 55 seconds on an IBM RS 6000 computer. Choosing a formulation that rules out most conflicts before the search begins shapes the fitness landscape the local search has to cross.

On 8-queens, then, hill climbing fails often but cheaply, and both remedies work. The 8-puzzle is a different story.

8-puzzle results

Instances

The script generated six sets of 1,000 instances.

  • Five are random walks of $d = 4$, 8, 16, 32, and 64 moves from the goal, never undoing the previous move.
  • The sixth draws uniformly from all solvable states, by shuffling the tiles and keeping a permutation only if its inversion count is even.

A random walk of $d$ moves is not an instance at distance $d$. Short walks reach few distinct states, and long walks partly undo themselves. So the table gives the true optimal solution lengths, taken from the breadth-first search.

Set Distinct states Mean optimal length $h_1$, no sideways $h_1$, 100 sideways $h_2$
depth 4 16 4.00 92.3% 100.0% 100.0%
depth 8 122 7.90 11.4% 29.1% 54.2%
depth 16 876 14.80 0.7% 1.9% 5.1%
depth 32 992 20.36 0.3% 0.6% 1.3%
depth 64 990 21.78 0.1% 0.1% 0.2%
uniform 998 22.06 0.1% 0.1% 0.1%

The table gives the percentage of instances that steepest-descent hill climbing solved, with random tie-breaking. One depth-32 walk happened to end at the goal itself, and it is counted as solved. Beyond the shallowest scrambles, hill climbing almost never solves the 8-puzzle with either heuristic.

A natural first guess is that a better heuristic would fix this. $h_2$ is the better estimate of distance, and it does help at depth 8: 54.2% solved, against 11.4% for $h_1$ without sideways moves and 29.1% with them. But from depth 16 on it solves about 5% at most. The exhaustive count below gives the reason: strict descent can succeed only from a state where the heuristic equals the true distance, and such states are rare.

Why it fails: an exhaustive count

The state space is small enough to examine completely. The breadth-first search gives the exact distance of every state from the goal: the largest is 31 moves, and the mean is 21.97. The script then scores every move from every state, 483,840 moves in all.

$h_1$ (misplaced tiles) $h_2$ (Manhattan distance)
Moves that leave $h$ unchanged 77.08% 0%
Moves that lower $h$ 11.46% 50.00%
Moves that raise $h$ 11.46% 50.00%
Non-goal states with no improving move 125,999 (69.44%) 44,291 (24.41%)
Non-goal states where $h$ equals the true distance 78 (0.04%) 2,350 (1.30%)

Plateaus dominate $h_1$. A move changes the position of exactly one tile, so $h_1$ changes only if that tile leaves its goal square or enters it. Most moves do neither, and 77% of all moves leave $h_1$ unchanged. In 69% of non-goal states no move lowers $h_1$, so a hill climber without sideways moves stops on its first step. Sideways moves let it wander these plateaus, which helps a little (11.4% to 29.1% at depth 8). But the solutions it finds are longer than necessary: at depth 16 the solved runs took 16.5 more steps than the optimal solution, on average.

Example (sideways moves under $h_2$). Allowing 100 sideways moves changes no run under $h_2$. A move shifts one tile by one square, along a row or along a column. That changes the tile's distance from its goal square in that direction by exactly 1, and leaves the other direction and every other tile alone. So the tile ends one square closer to its goal or one square farther away, and every move changes $h_2$ by exactly 1. There is never a neighbor of equal value, so the budget of sideways moves is never used, and the script's runs with and without it are identical.

The two 50.00% entries for $h_2$ in the table follow from the same fact. Every move can be undone by the opposite move, which changes $h_2$ by the opposite amount. So the moves pair off, one lowering $h_2$ and one raising it. The same pairing makes the lowering and raising shares equal for $h_1$.

$h_2$ has no plateaus, only local minima. The fitness landscape of $h_2$ has no flat regions at all, yet a quarter of all states are local minima, where every move leads uphill.

A single state shows how this happens. Take

$$\begin{array}{ccc} \_ & 1 & 5 \\ 3 & 7 & 4 \\ 2 & 6 & 8 \end{array}$$

which is 12 moves from the goal. Five tiles are misplaced (5, 7, 4, 2 and 6), so $h_1 = 5$. Their Manhattan distances are:

  • 1 for tile 5 (one row too high), 1 for 7, 1 for 4, and 1 for 6;
  • 4 for tile 2, two rows and two columns from its goal in the top-right corner.

So $h_2 = 8$. The blank is in a corner, so there are only two moves, and both raise $h_2$ to 9:

A local minimum of the Manhattan heuristic h2, 12 moves from the goal. The blank has two moves: sliding tile 1 left moves it off its goal square, and sliding tile 3 up does the same to tile 3, so both raise h2 from 8 to 9 and h1 from 5 to 6. Yet notice that the second move is the first step of an optimal solution, since it leads to a state 11 moves from the goal.
A local minimum of the Manhattan heuristic h2, 12 moves from the goal. The blank has two moves: sliding tile 1 left moves it off its goal square, and sliding tile 3 up does the same to tile 3, so both raise h2 from 8 to 9 and h1 from 5 to 6. Yet notice that the second move is the first step of an optimal solution, since it leads to a state 11 moves from the goal.

The second move is on an optimal path, so the optimal solution must begin by making $h_2$ worse. A heuristic that underestimates the distance by 4, as $h_2$ does here, leaves room for such detours, and strict descent cannot take them.

The exhaustive count also shows how the problem grows with the distance to the goal.

  • Panel (a) of the next figure plots the mean of each heuristic against the true distance. Both stay below the diagonal, as admissibility requires. But $h_1$ levels off near 7 (it cannot exceed 8), while $h_2$ keeps rising at a little over half the true distance.
  • Panel (b) plots the share of states at each distance where no move improves the heuristic, so that strict descent stops at its first step.
The 8-puzzle's 181,440 states grouped by their true distance from the goal. (a) Mean h1 and h2 at each distance, against the dotted line h = distance: both underestimate, h1 increasingly so. (b) The percentage of states with no improving move. Notice that it grows with distance for both heuristics, reaching 91% for h1 and 68% for h2 at distance 30. The zigzag comes from the position of the blank, which alternates between the corner and center squares at even distances and the edge squares at odd ones.
The 8-puzzle's 181,440 states grouped by their true distance from the goal. (a) Mean h1 and h2 at each distance, against the dotted line h = distance: both underestimate, h1 increasingly so. (b) The percentage of states with no improving move. Notice that it grows with distance for both heuristics, reaching 91% for h1 and 68% for h2 at distance 30. The zigzag comes from the position of the blank, which alternates between the corner and center squares at even distances and the edge squares at odd ones.

The zigzag in panel (b) has a simple cause. Every move carries the blank to an adjacent square. Coloring the board like a chessboard, the blank therefore changes color at every move. The goal has the blank in a corner, so at even distances the blank is on a corner or the center, and at odd distances on an edge square. A blank in a corner has only two moves, a blank on an edge has three, and a blank in the center has four. Four of the five squares used at even distances are corners. The count shows that states with fewer moves are more often without an improving one. Over all non-goal states, the share with no improving move is:

Blank on Moves $h_1$ $h_2$
Corner 2 81.2% 47.3%
Edge 3 62.5% 7.3%
Center 4 50.0% 1.2%

Strict descent can only succeed where the heuristic is exact. Here is the idea in one sentence. A successful strict descent walks down $h$ one unit per move, so its path is exactly as long as the heuristic says, and no path beats the true distance.

The argument in full: each move changes either heuristic by at most 1. A run without sideways moves lowers $h$ by exactly 1 at every step. So if it reaches the goal, it does so in exactly $h(s)$ moves from its start $s$. That path is a solution, so the optimal length $h^*(s)$ is at most $h(s)$. Admissibility gives $h(s) \le h^*(s)$. So $h(s) = h^*(s)$.

Strict hill climbing can therefore succeed only from the states where the heuristic is exactly right: 78 states for $h_1$ and 2,350 for $h_2$, out of 181,439. The condition is necessary but not sufficient, since a random tie-break can still step into a state where the heuristic underestimates. It explains both the collapse of the success rate beyond the shallowest scrambles and why every success without sideways moves in the experiment was an optimal solution.

A poor objective for hill climbing is not thereby a poor heuristic, as the next section shows.

A* with the same heuristics

The same heuristics that fail as hill-climbing objectives work well as guides for systematic search. A expands states in order of $g + h$, the cost so far plus the heuristic. With an admissible heuristic it returns an optimal solution (Russell and Norvig, 2020, §3.5.2). Both heuristics are also consistent, as the graph-search version in the script requires: a move costs 1 and changes either heuristic by at most 1. On the first 100 instances of every set, A with either heuristic solved all of them, and every solution length matched the breadth-first distance.

Set Mean optimal length Nodes expanded, $h_1$ (mean, median) Nodes expanded, $h_2$ (mean, median)
depth 16 14.78 439.0, 518 100.2, 82.5
depth 32 20.48 9,936.6, 4,221 1,121.1, 565.5
uniform 21.79 14,988.5, 7,947.5 1,524.9, 950

Here the better heuristic pays off directly: on uniform random instances, $h_2$ expands about a tenth as many nodes as $h_1$. A* never gets stuck, because it keeps every unexpanded state on its frontier and can always go back. Hill climbing keeps only the current state. When its one candidate path runs into a local minimum, nothing remains to fall back on.

The submitted programs beside the rerun

The assignment was submitted in January 2025 as two Python programs, one for each puzzle, and an eight-page report. The programs were written to show the search at work. Each draws the board at the start, after every move and at the end, and each runs a few instances drawn without a seed. How do its reported success rates, 20% on 8-queens and 33% on the 8-puzzle, fit with the rerun's 14% and 0.1%?

What the programs did. Both use steepest descent without sideways moves, the algorithm of the experiment section.

  • 8-queens. The state is a row number for each column, as here. The heuristic counts attacking pairs one pair at a time, adding one when two queens share a row and one when they share a diagonal. That gives the same total as the sum over lines, since two queens in different columns cannot share both a row and a diagonal. The 56 neighbors are generated column by column and, within a column, row by row. The program moves only to a strictly better neighbor and keeps the first one it finds at the lowest value, which is the experiment's first tie-breaking rule. It ran five random boards, then random restarts of up to 100 runs until one succeeded.
  • 8-puzzle. The heuristic is $h_1$, the number of misplaced tiles. The goal has tiles 1 to 8 in reading order with the blank in the bottom-right corner, and the blank is tried up, down, left and right, keeping the first lowest neighbor. The program ran three instances made by random walks of 10, 20 and 30 moves from the goal, walks that may undo their previous move. It then ran one configuration chosen by hand to show a local minimum.

The 8-puzzle goal differs from the one used here, but the results carry over. Turning the board half a turn and relabeling each tile $t$ as $9 - t$ maps one goal onto the other. The map takes moves to moves and leaves $h_1$ and $h_2$ unchanged, which the script checks on all 181,440 states. It turns each direction of the blank into its opposite, so it changes the order in which moves are tried, which matters only for breaking ties; the hand-picked run below is replayed under the submission's own goal and order.

What the report found. On 8-queens, one of the five boards was solved, a rate of 20%. The other four stopped with one or two attacking pairs, and the restart loop found a solution on its tenth run. On the 8-puzzle, the 10-move walk happened to end at the goal itself, so the report set it aside as trivial. The 20-move instance fell from 7 misplaced tiles to 5 in two moves and stopped. The 30-move instance, with 6 misplaced tiles, stopped without moving. The configuration chosen to show a local minimum reached the goal instead. One success among the three non-trivial instances gives the report's 33%.

Replaying the report's boards. The submitted rule breaks ties in a fixed order, so a run depends only on its starting board. The report lists its five 8-queens boards, so the companion script can replay them exactly. It reproduces all five final boards and final values of $h$ in the report's table. All four boards where the runs stopped have a neighbor of equal $h$. They are plateaus, like 98.6% of the failed runs in the rerun, and a climber allowed sideways moves would have continued from them.

Why the numbers differ. Four differences between the submission and the rerun account for the gap, and only the last two matter here.

  • Tie-breaking. The submission's rule is the rerun's first rule, which solved 14.68% of 30,000 boards without sideways moves, against 14.02% for random ties. Without sideways moves the rule barely matters. With sideways moves it would have mattered a great deal: 32.45% against 94.28%.
  • Move limits. The submission stops at the first step that does not improve $h$. A strict descent always ends, because $h$ falls at every move, so no step limit was needed. The rerun's 94% belongs to a different algorithm, one with a budget of 100 sideways moves. The comparable row of the 8-queens table is the one without sideways moves.
  • Sample size. One success in five runs is consistent with a true rate of 14.68%. The exact (Clopper–Pearson) 95% interval for one success in five runs is 0.5% to 71.6%; Confidence Intervals for a Proportion derives that interval from the binomial tails. At $p = 0.1468$, exactly one success in five runs has probability 38.9%. The tenth-run restart is also unremarkable: a first success at the tenth run or later has probability $(1 - p)^9 = 24\%$.
  • Choice of instances. The 33% on the 8-puzzle is not a rate over random instances. Its one success was the configuration chosen by hand, which is two moves from the goal with $h_1 = 2$. It is one of the states where the heuristic equals the true distance, from which strict descent can succeed. Both random-walk instances that were not trivial stopped, as nearly all do in the rerun at those depths: 0.7% of depth-16 and 0.3% of depth-32 instances were solved under $h_1$ without sideways moves. A walk that may undo its moves also ends nearer the goal than its length suggests, which is how a 10-move walk returned to the goal.

The submission and the rerun agree, then: where they run the same algorithm on comparable instances, the rates differ by no more than five runs can resolve.

Worked problem: the assignment

This section states the course's first assignment and answers it in one place. Every figure in it is from the experiments above or from the traces below, which tools/experiments/evolution/puzzles_examples.py prints and checks.

Problem. Implement hill climbing for the 8-puzzle, with the number of misplaced tiles as the heuristic, and for 8-queens, with the number of attacking pairs. Report runs that succeed and runs that get stuck. Explain how random restarts help.

Approach. Both puzzles use the same steepest-descent hill climber, specified in the experiment section: score every neighbor, move to one with the lowest $h$, and stop when no neighbor is strictly better. The assignment leaves two things open, and each was settled by measurement.

  • Ties. Random tie-breaking, for the reason shown in the 8-queens results.
  • Why runs stop. Success rates do not say why a run stops. For 8-queens the stopped runs were replayed and classified. For the 8-puzzle all 181,440 states were counted, and a second heuristic, $h_2$, was run for comparison.

8-queens: a run that succeeds. The board $(1, 2, 2, 3, 2, 7, 6, 3)$ is the first seeded random board from which the descent reaches a solution. It has $h = 10$:

  • three queens on row 2 (columns 1, 2 and 4), 3 pairs;
  • three queens on one diagonal (columns 2, 3 and 6), 3 pairs;
  • four lines with two queens each: row 3 (columns 3 and 7) and three diagonals (columns 0 and 1, columns 3 and 4, columns 5 and 6), 4 pairs.
Step $h$ Best neighbor $h$ Moves tied for best Move made
0 10 6 1 column 2, row 2 to 5
1 6 4 1 column 3, row 3 to 0
2 4 2 2 column 1, row 2 to 7
3 2 0 1 column 5, row 7 to 4
4 0 stop: solved

The run ends at $(1, 7, 5, 0, 2, 4, 6, 3)$ after four moves. That board is a solution. Its rows are all different. So are the sums of row and column, which are $1, 8, 7, 3, 6, 9, 12, 10$, and the differences of row and column, which are $1, 6, 3, -3, -2, -1, 0, -4$. So no two queens share a row or a diagonal.

8-queens: runs that get stuck. The worked descent near the top of this article is one. It falls from 17 to 1 in four moves and stops on a plateau, with two neighbors of equal $h$ and none lower. The strict local minimum pictured after it is the rarer kind of stop, where every move makes $h$ worse.

8-puzzle: a run that succeeds. The state below is 8 moves from the goal, and all eight tiles are misplaced, so $h_1 = 8$ as well.

$$\begin{array}{ccc} 1 & 4 & \_ \\ 6 & 3 & 2 \\ 7 & 8 & 5 \end{array}$$

At every step exactly one move lowers $h_1$, and it slides a tile onto its goal square:

Step Tile moved into the blank $h_1$ after the move True distance after the move
1 2, up 7 7
2 5, up 6 6
3 8, right 5 5
4 7, right 4 4
5 6, down 3 3
6 3, left 2 2
7 4, down 1 1
8 1, right 0 0

The run reaches the goal in 8 moves, which is optimal. It succeeds because at every state exactly one move lowers $h_1$. Along the way $h_1$ equals the true distance at every state, as it must for strict descent to succeed (the necessary condition proved above). Only 78 non-goal states meet that condition.

8-puzzle: runs that get stuck. The first instance of the uniform set is typical:

$$\begin{array}{ccc} 5 & 3 & \_ \\ 4 & 7 & 6 \\ 1 & 8 & 2 \end{array}$$

It is 22 moves from the goal, and all eight tiles are misplaced, so $h_1 = 8$. The blank is in a corner and has two moves, sliding tile 3 right or tile 6 up. Neither tile lands on its goal square, so both moves leave $h_1$ at 8. No neighbor is strictly better, and the run stops without making a move. This is a plateau. With sideways moves the run would wander across it. The same two moves raise $h_2$ from 16 to 17, so under $h_2$ the state is a local minimum. The state pictured in the exhaustive count is the other kind of stop under $h_1$: both of its moves raise $h_1$ from 5 to 6. The 8-puzzle table gives the success rates.

How random restarts help. On 8-queens a restart draws a fresh board and any solution will do, so runs are independent trials. The section on random restarts shows that about 7 runs and 23 moves suffice on average, and every one of 10,000 restart trials succeeded. On the 8-puzzle a fresh random state is a different instance, so restarts do not help in the same way, as the next section explains.

Result. Hill climbing with the assigned heuristics solves 8-queens cheaply once restarts or random sideways moves are added, and rarely solves the 8-puzzle beyond the shallowest scrambles.

What the two problems teach

Local search suits problems where only the final state matters. In 8-queens, any arrangement with no attacks is a solution, and the path to it is irrelevant. In the 8-puzzle, the start state is fixed and the sequence of moves is the answer. Russell and Norvig (2020, §4.1) draw the same distinction: local search is designed for problems in which the path to a goal does not matter. The 8-puzzle can be forced into the local-search mold, as the assignment did, but it is a path-finding problem.

Restarts need a problem that can be restarted. For 8-queens, a fresh random board is another valid starting point, and with $p = 0.14$ a solution arrives after about seven runs. For an 8-puzzle instance, a fresh random state is a different instance. Repeating runs from the same start state with random tie-breaking can still help, but without sideways moves only from the small set of states where descent can succeed at all.

The heuristic shapes the search space. For A, $h_2$ beats $h_1$ by being larger while still admissible. It is at least as large in every state, since each misplaced tile is at least one square from its goal. Russell and Norvig (2020, §3.6.1) explain that when one admissible heuristic dominates another in this way, A with it never expands more nodes, apart from ties. For hill climbing, what matters is the shape of the surface: $h_1$ is mostly flat, and $h_2$ has no flat regions but many pits. The same function can be a good estimate of distance and a poor objective for local search. Each heuristic, together with the move set, defines its own fitness landscape, a point that fitness landscapes makes about variation operators.

Sideways moves are a random walk, and they need randomness. On 8-queens, 100 sideways moves raise the success rate from 14% to 94% with random tie-breaking. With a fixed tie-breaking rule they raise it only to 32%, because deterministic sideways moves cycle. On the 8-puzzle under $h_1$, they help a little and lengthen the solutions. Under $h_2$, which has no plateaus, they do nothing.

What we have learned

On 8-queens, nearly every failure is a near miss on a plateau, so random sideways moves and restarts both work, at about 23 steps per solution either way. On the 8-puzzle, the heuristics are either mostly flat or full of pits, and strict descent can succeed only where the heuristic is exact. The puzzle is a path-finding problem, and A* with the same heuristics solved every instance it was given.

These are the problems that the rest of the course addresses with populations. A genetic algorithm keeps many candidates rather than one. That is a different answer to the question that restarts and sideways moves answer: how to keep searching after the nearest local optimum. The next topic, genetic algorithms, begins with the simple genetic algorithm.

References

  • Johnson, W. W., and Story, W. E. (1879). Notes on the "15" puzzle. American Journal of Mathematics, 2(4), 397–404. record
  • Russell, S., and Norvig, P. (2020). Artificial Intelligence: A Modern Approach, 4th ed., sections 3.5.2, 3.6, 3.6.1, 4.1, and 4.1.1. Pearson. record · 6 pages
  • Sosič, R., and Gu, J. (1990). A polynomial time algorithm for the N-queens problem. ACM SIGART Bulletin, 1(3), 7–11. record
  • Sosič, R., and Gu, J. (1991). 3,000,000 queens in less than one minute. ACM SIGART Bulletin, 2(2), 22–24. record

Reviewed: verified, 23 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 10 revisions