AI Wiki中文/EN

Hill climbing

爬山法

Follow strict best-improvement moves on an N-queens board, verify local stops, and calculate what independent restarts can promise.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Move the queen that removes the most conflicts

Place four queens on a four-by-four chessboard, one in each column. All four initially share row 0. Every pair attacks, so there are six conflicts. Move one queen within its column, inspect the resulting conflicts, and choose the move with the largest reduction. Repeat. This is steepest-descent hill climbing applied to a cost we want to minimize.

The name can sound backwards: why climb when the cost decreases? A maximization problem climbs its score; minimizing a cost is equivalent to maximizing its negative. The defining choice here is to inspect every neighbor and accept a strictly better one. Berkeley’s hill-climbing section describes the corresponding steepest-ascent rule and its failure at local optima. CS188, section 1.5.1

Represent a board as (row_in_column_0, row_in_column_1, ...), with rows and columns numbered from 0. Thus (1,3,0,2) puts the first queen in row 1, the second in row3, and so on. This encoding guarantees one queen per column. Row and diagonal attacks remain possible.

With the deterministic tie rule used below, the all-zero start reaches (1,3,0,2), a valid solution, with conflict counts 6 → 3 → 1 → 0. Start at (0,1,3,2) instead and the same algorithm stops immediately at cost 2. Trying harder to choose the best single move does not help: every neighbor has at least two conflicts. The question is now about the allowed moves and stopping rule.

What strict improvement proves

For an nn-queen board qq, let qiq_i be the row of the queen in column ii. The complete state space has nnn^n assignments, including boards with conflicts. A neighbor changes exactly one queen’s row to one of the other n−1n-1 rows, giving n(n−1)n(n-1) distinct neighbors. Define the cost by counting attacking pairs once:

C(q)=∑0≤i<j<n1[qi=qj  ∨  ∣qi−qj∣=j−i].C(q)=\sum_{0\le i<j<n}\mathbf{1}\bigl[q_i=q_j\;\lor\;|q_i-q_j|=j-i\bigr].

The indicator is 1 if the enclosed condition holds and 0 otherwise. Equal rows account for horizontal attacks; equal row and column separation identifies a diagonal. Column attacks are excluded by the encoding. Counting conflicted queens would be a different objective: one queen can participate in several conflicting pairs.

Write N(q)N(q) for this neighborhood. After checking for zero cost, choose a neighbor with the smallest cost and accept it only when it improves the current board:

y∈arg⁡min⁡z∈N(q)C(z),C(y)<C(q)⟹qnext=y.y\in\arg\min_{z\in N(q)} C(z),\qquad C(y)<C(q)\Longrightarrow q_{\mathrm{next}}=y.

A solution satisfies C(q)=0C(q)=0, which is a known global lower bound. A positive-cost stopping board satisfies

C(q)≤C(z)(∀z∈N(q)).C(q)\le C(z)\qquad(\forall z\in N(q)).

This is a local minimum in the non-strict sense: equal-cost neighbors are allowed. It may lie on a plateau with an escape elsewhere. The word “local” always refers to this particular neighborhood. Allowing two queens to move at once produces a different test. Poole and Mackworth distinguish local and global optima and explain why positive conflicts at a local minimum do not establish that a constraint problem is unsatisfiable. Section 4.6.1

Strict improvement prevents cycles. Here the cost is an integer between 0 and n(n−1)/2n(n-1)/2, so every accepted move removes at least one conflict. If rr moves are accepted from q(0)q^{(0)}, then

r≤C(q(0))≤n(n−1)2.r\le C\bigl(q^{(0)}\bigr)\le\frac{n(n-1)}{2}.

This proves termination for an unrestricted run of this finite example. It does not prove arrival at zero. With a general real-valued objective on a finite state space, strict descent still cannot revisit a state, but the integer cost bound no longer applies. On an infinite state space, strict decreases alone do not establish finite termination.

An exact, small-board baseline

This complete Python 3.10+ program accepts a finite iterable containing one integer row per column. A board must be nonempty; each row must lie in 0..n-1. Boolean rows and a Boolean step budget are rejected even though Python treats booleans as integers. conflicts is an internal scoring helper for valid boards; hill_climb checks its input before calling it.

A sweep examines all neighbors of the unchanged current board. Columns are scanned in increasing order, then destination rows. A strict comparison preserves the first move among equally good improvements. Changing this tie rule can change which solution or local minimum is reached.

max_steps limits complete neighbor sweeps. The return value is (status, final_board, conflict_trace). solved means zero conflicts; local means a full sweep found no improving neighbor; limit means the budget ended without either certificate. The trace includes the initial cost and costs after accepted moves. A zero budget still recognizes an already solved board, but an unsolved board receives limit without a neighborhood check.

def conflicts(board):
    return sum(board[i] == board[j] or abs(board[i]-board[j]) == j-i
               for i in range(len(board)) for j in range(i+1, len(board)))


def hill_climb(board, max_steps=100):
    board = tuple(board)
    n = len(board)
    if not n or any(type(row) is not int or not 0 <= row < n for row in board):
        raise ValueError('supply one row in 0..n-1 for each of n columns')
    if type(max_steps) is not int or max_steps < 0:
        raise ValueError('max_steps must be a nonnegative integer')
    value = conflicts(board)
    trace = [value]
    if value == 0:
        return 'solved', board, trace
    for _ in range(max_steps):
        best, best_value = board, value
        for col in range(n):
            for row in range(n):
                if row == board[col]:
                    continue
                candidate = board[:col] + (row,) + board[col+1:]
                candidate_value = conflicts(candidate)
                if candidate_value < best_value:
                    best, best_value = candidate, candidate_value
        if best_value == value:
            return 'local', board, trace
        board, value = best, best_value
        trace.append(value)
        if value == 0:
            return 'solved', board, trace
    return 'limit', board, trace

from collections import Counter
from itertools import product

print(hill_climb((0, 0, 0, 0)))
print(hill_climb((0, 1, 3, 2)))
print(hill_climb((0, 0, 0, 0), max_steps=1))
outcomes = Counter(hill_climb(b)[0] for b in product(range(4), repeat=4))
print(dict(outcomes))

The four outputs are:

('solved', (1, 3, 0, 2), [6, 3, 1, 0])
('local', (0, 1, 3, 2), [2])
('limit', (0, 3, 0, 0), [6, 3])
{'solved': 101, 'local': 155}

The final line enumerates all 44=2564^4=256 starts, using the default budget 100. No run exhausts that budget: the integer bound allows at most six accepted moves and at most one final non-improving sweep. Of the 101 successful starts, 52 reach (1,3,0,2) and 49 reach (2,0,3,1). These are the two zero-conflict boards found by direct enumeration. Among the 155 other starts, 137 stop at cost 1 and 18 at cost 2. These are results of this exact program and tie rule, not success rates for hill climbing in general.

The repository checks the scorer against a separate count of pairs sharing a row or either diagonal. It also constructs the entire four-queen neighborhood graph independently, compares the deterministic descent from every start, and checks each local stopping board against all its neighbors. The two implementations use different conflict-counting methods, so agreement is stronger evidence than replaying the same formula twice.

This readable implementation favors explicit work over speed. Scoring one board takes O(n2)O(n^2) time. A sweep scores n(n−1)n(n-1) candidates, taking O(n4)O(n^4) time; copying a tuple costs O(n)O(n) per candidate and does not increase that bound. For KK sweeps, total time is O(n2+Kn4)O(n^2+Kn^4). The code holds a few boards and an energy trace, so auxiliary space is O(n+r)O(n+r) for rr accepted moves. It never stores all neighbors simultaneously.

A faster version can maintain counts for rows and both diagonal families. Moving one queen changes only the pairs involving that queen. After temporarily removing it from those counts, a destination score can be computed from the three destination counts in constant time. Scanning all destinations then costs O(n2)O(n^2) per sweep, with O(n)O(n) bookkeeping. That is an optimization exercise; the code above deliberately recomputes each full score. Poole and Mackworth discuss the broader cost of choosing the most improving move and alternatives that examine fewer choices. Section 4.6.3

A plateau, a budget, and a restart

The stopping board (0,1,3,2) has an escape if equal-cost moves are permitted. Each transition below changes one queen:

BoardConflicts
(0,1,3,2)2
(0,3,3,2)2
(0,3,0,2)1
(1,3,0,2)0

Our strict rule rejects the first transition. A sideways-move variant could take it, but permitting equality also permits cycles. Such a variant needs its own move-selection and termination policy. A random step may cross a rising cost; a restart replaces the whole starting assignment. Berkeley describes sideways moves and restarts, while Poole and Mackworth’s “iterative best improvement” can continue to an equal or worse best neighbor. That latter stopping policy differs from the strict rule implemented here. CS188, section 1.5.1, Poole and Mackworth, sections 4.6.1–2

Restarts allow a precise probability statement for this small experiment. Suppose each trial draws a fresh board uniformly from the 256 starts, independently of every other trial, and runs the unchanged algorithm with enough sweeps. The single-trial success probability is p=101/256p=101/256. For RR trials, write PRP_R for the probability of at least one success:

PR=1−(1−p)R.P_R=1-(1-p)^R.

Five trials succeed with probability about 0.918631. This counts five independent trials in total, including the first initialization. Reusing the same board and deterministic tie rule gives no such improvement. Biased starts, dependent trials or a smaller sweep budget change pp or invalidate the product calculation.

When p>0p>0, the displayed probability approaches 1 as the number of independent trials grows without bound. Under these assumptions, this is probabilistic completeness for finding a solution. Any fixed finite budget still permits failure. If no solution exists, random restarts cannot produce one and do not provide an unsatisfiability proof. General optimization also needs a way to recognize the sought optimum; queens have the convenient zero-conflict certificate.

Discrete steepest descent and gradient descent share a preference for decreasing an objective. Their actual operations differ: this program enumerates discrete neighbors, while a gradient method uses derivatives and a step size in a continuous space. No derivative is taken here. A change in coordinates, neighborhood or tie handling can alter the run even when the objective is unchanged.

Check the move, then check the claim

  1. Count pairs by hand. What are the costs of (0,0,0,0) and (1,3,0,2)? Why should a queen with three attackers contribute to three pairs?
    Answer: The first board has six pairs in one row, so its cost is 6. The second has no equal rows or attacking diagonals, so its cost is 0. The objective counts violated pair constraints; it does not merely count how many queens are in trouble. Each pair is counted once by the condition i<ji<j.

  2. Read the stopping label. An unsolved board is passed with max_steps=0. Can the returned status prove local optimality? What about (0,1,3,2) with a budget of 1?
    Answer: A zero budget returns limit after scoring the initial board; no neighbors were inspected. For (0,1,3,2), one complete sweep finds no improvement and returns local at cost 2. The plateau path above shows that this local certificate does not rule out a solution reachable through equal-cost moves.

  3. Quantify restarts. For the exact four-queen experiment, what is the failure probability after five independent uniform trials? What changes if the identical start is repeated?
    Answer: The probability is (155/256)5(155/256)^5, approximately 0.081369. Deterministically repeating one start repeats its outcome; there are no five independent chances. The success probability 101/256 applies only to the specified distribution, tie rule and sufficient sweep budget.

  4. Explain the faster scorer. Remove a queen in column ii before testing a new row uu. Which counts determine the new conflicts involving that queen? Does an O(n2)O(n^2) sweep prove the search will solve the puzzle?
    Answer: Add the count for row uu, the descending-diagonal index u−iu-i, and the ascending-diagonal index u+iu+i, all with that queen removed. Distinct columns ensure another queen cannot share two of these three attack lines with the candidate, so the sum counts its conflicting pairs once. Subtract its old conflicts and add its new conflicts to update the total. The cheaper sweep preserves the same local decision when ties are handled identically; it gives no new global guarantee.

What to compare next

This article isolates strict steepest descent. The local-search overview discusses how to choose a representation and neighborhood. A continuation into simulated annealing changes the acceptance rule to permit some increases in cost. Each comparison should hold the queen encoding and objective fixed before attributing a result to the search policy.

For an experiment, record success over a stated distribution of starts, conflict counts at unsuccessful stops, accepted moves, and total score evaluations. A method that needs fewer moves may inspect far more neighbors. Compare elapsed time only after recording the implementation and environment. Keep solution verification separate from the solver: a candidate’s pair count is easy to check even when the search procedure is complicated.

The cited course and textbook supply the algorithmic definitions and variants. The code, plateau example, termination calculation and 256-start enumeration in this article were constructed and checked for this edition. They are a teaching baseline, with no claim to reproduce a large-board benchmark or an original historical implementation.

Make a prediction, then check

A board has two conflicting pairs, and a complete sweep finds no single-queen move that strictly lowers the cost. What does this prove?

Choose one answer

Learning objectives

  • Define the queen-pair objective, trace strict steepest descent and prove its stopping bound.
  • Distinguish local stops, exhausted budgets and plateau escapes, then calculate independent-restart probabilities for a specified start distribution.

Prerequisites & connections

Explore related knowledge →

References

  1. CS188 Textbook: 1.5 Local Search
    UC Berkeley CS188 course staff
  2. Artificial Intelligence: Foundations of Computational Agents, third edition, 4.6 Local Search
    David L. Poole; Alan K. Mackworth

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check:primary-source locations,original executable examples,independent finite-state oracles,bilingual review and a second Codex agent cross-check;not independent human peer review.

  • Compared bilingual encoding, tie order, three statuses, termination proof, complexity, plateau path and all four answered exercises; display equations and Python blocks match byte for byte.
  • Seven independent tests passed: row/two-diagonal counters against every 1–5-queen board and larger random boards; independent Hamming graph for all 256 starts with budgets 0–7; exact 101/155, 52/49 and 137/18 counts, plateau escape, 8-queen local certificate, incremental scoring, restart-pair enumeration and invalid inputs.
  • Executed the complete example and matched all four outputs; corrected the draft one-step board to (0,3,0,0). Prose scan passed; no independent human expert review or large-scale performance reproduction.
  • Another Codex agent independently checked all256starts,101/155outcomes,52/49basins,score-call counts and1–3queen boundaries; five independent restarts gave0.918631058903884. No substantive issue found.
  • Paired code,display formulas and main anchors match. All48search checks and101article Python programs passed. Reviews are AI technical checks,not independent human peer review.

Source locations checked:

  • CS188 Textbook: 1.5 Local Search · Read §1.5.1, lines 96–103: best-improving hill climbing, plateaus, sideways moves and random restart. Also §1.5.4, lines 119–122 for one queen per column. Do not adopt the page’s unqualified “trivially complete” restart statement or equate discrete neighbor enumeration with gradient descent.
  • Artificial Intelligence: Foundations of Computational Agents, third edition, 4.6 Local Search · Read §4.6.1–3, lines 62–118: conflict objective, local/global distinction, positive local cost not an unsatisfiability certificate, allowance for worse/equal best neighbors, restart/random-step distinction and cost of choosing a move. Counter-based queen update and exact 256-state counts were independently constructed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.