← MAIN
08 // LOCAL SEARCH

N-QUEENS

Place N queens so that none attacks another. Four agents solve the same board.
MODE PLAY CONFLICTS — STEPS 0

HOW TO PLAY

Place N queens on an N × N board so that no two queens attack each other. A queen attacks along its column and both diagonals, so each row holds exactly one queen.

In PLAY, click a square to put a queen in its row, and click it again to take the queen back. HINT names the next min-conflicts move.

WATCH replays one agent's search step by step. RACE runs all four agents on one board, and BIG N runs min-conflicts live in your browser.

Click a square to put a queen in its row. A red queen is in conflict; pink squares glow by how many queens attack them.
HOW THE FOUR AGENTS DIFFER

HOW IT WORKS

N-queens asks for N queens on an N × N board so that no two attack each other. Four agents attempt it. Backtracking is a systematic search, so it can prove that no solution exists. The other three are local search methods: they start from a board that has conflicts and change one queen at a time to reduce them, so they cannot prove that no solution exists. Min-conflicts is the agent that scales. In the benchmark it solved a 1,000,000-queen board in one run of 13.6 s.

The board and the conflict count

The board has one queen per row, so only columns and diagonals can clash. A conflict is a pair of queens that share a column or a diagonal. A diagonal is a line of squares at 45 degrees. Squares on one diagonal satisfy either r + c = constant or r − c = constant, so the board keeps two arrays for the diagonals, one for each family, with 2n − 1 entries each1.

The conflict count is the number of attacking pairs on the board. A line that holds k queens contains C(k, 2) = k(k − 1) / 2 pairs. No two queens share two lines, because a shared column and a shared diagonal would put them in the same row, and two shared diagonals would put them on the same square. So the conflict count is the sum of C(k, 2) over every line2.

3
\text{conflicts} = \sum_{\ell} \binom{k_\ell}{2} = \sum_{\ell} \frac{k_\ell\,(k_\ell - 1)}{2}

Here ℓ runs over every column and every diagonal of both families, and k_ℓ is the number of queens on line ℓ. The function that computes this sum from scratch is count_conflicts, and the tests check it against a brute-force pair count. The board does not recount on each move. place adds the queens already on a new queen's three lines, and remove subtracts the queens left behind on the lines of the queen it takes away45.

The attack count A(r, c) is the number of queens that would attack a queen placed on square (r, c), not counting the queen already in row r. The three lookups read the column and the two diagonals through (r, c)6.

6
A(r,c) = \mathrm{col}[c] + \mathrm{d1}[r + c] + \mathrm{d2}[r - c + n - 1] - 3\,[\,\mathrm{cols}[r] = c\,]

Here [·] is 1 when the condition holds and 0 otherwise. If the row-r queen stands on (r, c) itself, it lies on all three lines, so 3 is subtracted. Otherwise the row-r queen is on none of them, because its lines meet (r, c) only when it is in column c. Each lookup is O(1), so every agent scores a move without rescanning the board.

Backtracking with bitmasks

Backtracking is a depth-first search of a search tree. The tree has one level per row, and each node is a partial placement with a queen in every row above. The search places a queen in the lowest open column of the current row. When a row has no open column, the search backtracks: it takes back the queen in the row above and tries that queen's next open column. The search is exhaustive, so when it ends with no solution it has proved that none exists, as it does for N = 2 and N = 37.

A bitmask is an integer in which bit c stands for column c, so a set of columns is one number and a set operation is one bitwise instruction. For row r the search keeps three n-bit masks: C, the columns already taken; L (ld), the columns hit by one family of diagonals from queens above; and R (rd), the columns hit by the other family. A queen in column c blocks column c + 1 one row lower through L and column c − 1 through R8.

9
\mathrm{open}_r = F \land \lnot\,(C_r \lor L_r \lor R_r), \qquad b = \mathrm{open}_r \land (-\mathrm{open}_r)

Here F = 2n − 1 is the mask with all n columns set, ∧ is bitwise AND, ∨ bitwise OR and ¬ bitwise NOT (the code writes &, | and ~). The open columns of row r are the columns that none of the three masks takes. The bit b is the lowest open column, and the search tries it first. The code computes b as bits & -bits9.

10
C_{r+1} = C_r \lor b, \qquad L_{r+1} = \bigl((L_r \lor b) \ll 1\bigr) \land F, \qquad R_{r+1} = (R_r \lor b) \gg 1

Here ≪ and ≫ are left and right bit shifts, and r + 1 is the next row. Placing a queen in row r sets its bit in C, and its two diagonals move one column per row, which the shifts express. The next row's open columns are then computed from the three new masks with the formula above11.

12
function BACKTRACK(n):
    row ← 0
    open[0] ← every column
    while row < n:
        if open[row] is empty:
            if row = 0:
                return "no solution exists"
            row ← row − 1                      # backtrack: take back the queen above
        else:
            c ← the lowest open column of row
            remove c from open[row]
            place a queen at (row, c)
            row ← row + 1
            open[row] ← columns not taken and not on a diagonal of a queen above
    return the placement

Bit tricks. bits AND (−bits) isolates the lowest set bit, and bits XOR bit clears it. Both are single machine operations, so the search never loops over the columns of a row to find the next one to try.

Iterative search. The search keeps one array entry per row instead of recursing, because a recursion of depth 10,000 would overflow Python's stack7.

Recording omitted. The full version leaves out the trace and frame recorder, which only keeps the samples the chart and the watch view read. It does not change the search.

Steepest-ascent hill climbing

Hill climbing is a local search. It starts from a complete placement, one queen per row on a random column, and changes it one move at a time. A move puts the row-r queen on column c. The code calls the method steepest ascent: each step scores every move and plays the one that removes the most conflicts13. Scoring all moves costs n² squares per step.

A placement where no move lowers the conflict count is a local minimum or lies on a plateau, a region where the count stays level. The code allows no sideways moves, so at such a placement it restarts from a random placement. A restart counts as a step and as a restart14.

15
\Delta(r,c) = A(r,c) - A(r,\,\mathrm{cur}_r)

Here Δ(r, c) is the change in conflicts if the row-r queen moves from column curr to column c. A is the attack count above, and A(r, curr) is the number of queens attacking the row-r queen. The code computes the same number as col[c] + d1[r + c] + d2[r − c + n − 1] − base, with base already holding A(r, curr). A move is useful when Δ < 0. The step keeps every move with the most negative Δ and plays one of them at random16.

17
function HILL-CLIMB(n):
    board ← RANDOM-PLACEMENT(n)               # one random column per row
    while board has conflicts:
        best ← the moves that lower the conflict count the most
        if best is not empty:
            play one move from best, chosen at random
        else:
            board ← RANDOM-PLACEMENT(n)       # local minimum or plateau: restart
    return board

The base term. The row's own queen is counted on its column and both diagonals, so base subtracts those three counts of 1 to leave only the other queens. Subtracting base from every candidate's count turns the count into a change in conflicts.

Ties. Several moves often share the best Δ. The step picks one of them at random, so the search does not always follow the same order over the rows.

Simulated annealing

Simulated annealing is a local search that sometimes accepts a move that raises the conflict count. How often it does so is set by a temperature T, which falls during each run. While T is high the search wanders; as T falls it settles18.

Each step is a proposal. A random row r is chosen, and its queen moves to a random other column c. Every column other than the current one is equally likely. The change in conflicts is Δ(r, c), defined as above. The code decides on the proposal with the rule below, where the acceptance probability is written out for both cases19.

20
\Pr[\text{accept}] = \begin{cases} 1 & \Delta \le 0 \\ e^{-\Delta / T} & \Delta > 0 \end{cases}

Here e is the base of the natural logarithm and T is the current temperature. A proposal that does not raise the count is always taken. An uphill proposal with Δ > 0 is taken with probability e−Δ/T, so a small increase is often accepted while T is high and rarely once T is low. Example. At T = 2.0, an uphill move with Δ = 1 is accepted with probability e−0.5 ≈ 0.61.

The temperature falls geometrically from T0 = 2.0 to T1 = 0.05 over a run of L = max(200, 60 n) proposals. The code multiplies the temperature by a fixed factor after each proposal21.

22
\mathrm{cool} = \left(\frac{T_1}{T_0}\right)^{1/L}, \qquad T_k = T_0 \cdot \mathrm{cool}^{\,k}

Here k counts the proposals made since the start of the run, so T0 is the temperature at k = 0. After L proposals the temperature has reached T1, because coolL = T1 / T0. The code multiplies the temperature by cool after each proposal23. Example. At n = 8, L = 480 and cool ≈ 0.9923, so T falls from 2.0 to about 0.32 after 240 proposals.

24
function ANNEAL(n):
    board ← RANDOM-PLACEMENT(n)
    T ← 2.0
    while board has conflicts:
        r ← a random row;  c ← a random column other than the one in row r
        d ← change in conflicts if the row-r queen moves to c
        if d ≤ 0 or a random number in [0, 1) < exp(−d / T):
            MOVE(board, r, c)                  # accept the proposal
        T ← T × cool
        if the run is over:
            board ← RANDOM-PLACEMENT(n)        # start a new run
            T ← 2.0
    return board

Column offset. The new column is (cur + 1 + randrange(n − 1)) % n. The offset is between 1 and n − 1, so the proposal is never the current column, and each of the other n − 1 columns is equally likely25.

Restarts. A run that ends unsolved starts again from a fresh random placement at T = 2.0. Each run is an independent attempt, and max_steps caps the total number of proposals across all runs.

Min-conflicts

Min-conflicts is a local search introduced by Minton, Johnston, Philips and Laird in 1992. It starts from a greedy start, a placement with few conflicts, and then repeats one repair. A repair picks a queen in conflict, lifts it, and puts it back on the column of its row with the fewest attacks. The lifted queen's old column is one of the candidates, so a repair never raises the conflict count26.

The greedy start fills the rows from top to bottom. Each row tries up to 4,096 random unused columns and keeps the first column that no queen attacks, or else the least attacked column tried. An unused column has no queen on it, so the attack count of such a column is given by the two diagonal counts alone27.

28
a_c = \mathrm{d1}[r + c] + \mathrm{d2}[r - c + n - 1]

Here ac is the attack count of unused column c in row r, and the search keeps the smallest ac it has seen. Only unused columns are tried. A used column already has a queen attacking along it, so it can never be attack-free for the row29. The greedy start leaves some conflicts near the end of the fill, when few free diagonals remain. The code's docstring records a one-off check, not committed, that left about 10 conflicts at 1,000 to 10,000 queens30.

A queen in row r is in conflict when its row's count is more than 3. Its own three lines contribute 3, so any higher count means another queen shares one of its lines31.

31
S_r = \mathrm{col}[c_r] + \mathrm{d1}[r + c_r] + \mathrm{d2}[r - c_r + n - 1] \;>\; 3

Here cr is the column of the row-r queen, and the inequality marks a queen in conflict. Equivalently, the queen's attack count A(r, cr) is greater than 0.

A repair chooses a conflicted row uniformly at random, lifts its queen, and scores every column of that row with the same count, now without the queen32.

32
\mathrm{score}(r,c) = \mathrm{col}[c] + \mathrm{d1}[r + c] + \mathrm{d2}[r - c + n - 1], \qquad c_{\text{new}} \in \arg\min_c \mathrm{score}(r,c)

Here score(r, c) is the attack count of square (r, c) with the row-r queen lifted, so it equals A(r, c) for every column. The new column is drawn uniformly from the columns with the smallest score. The code computes all n scores in one pass over the numpy arrays33.

Plateau restart. Repairs can cycle between placements that have the same conflict count. If the count has not reached a new low for more than max(200, 20 n) repairs, the run starts again from a new greedy start34.

3536
function MIN-CONFLICTS(n):
    cols ← GREEDY-START(n)                     # few conflicts to begin with
    repeat until conflicts = 0:
        r ← a random row whose queen is in conflict
        lift the queen in row r
        c ← a column of row r with the fewest attacks, ties at random
        place the queen at (r, c)
        if the count has not reached a new low for a long time:
            cols ← GREEDY-START(n)             # plateau: start again
    return cols

Finding a conflicted row. Trying random rows is cheap while conflicts are common. When they are rare, most random rows are clean, so after 4,000 misses one pass lists every conflicted row. Both paths choose uniformly from the conflicted rows, so the rule is the same either way37.

Free-column list. The greedy start keeps the unused columns in a list. Taking a column out is a swap with the last entry and a pop, so each removal is O(1) and a late row does not scan the whole board.

Why it scales. Each repair scores one row of n columns, and the greedy start leaves few conflicts. The committed benchmark's median repair count over solved runs is 24 at 8 queens, 116 at 100,000 queens and 47 at 1,000,000 queens. Across every size it runs from 24 to 11638.

Parameters and their values

ParameterValueUsed by
Queens per rowExactly 1 (conflicts are columns and diagonals only)all
Column orderLowest open column firstbacktracking
Move choiceBest move; ties at random; no sideways moves; restart at a local minimumhill climbing
Start and end temperatureT0 = 2.0, T1 = 0.05, geometric coolingannealing
Run lengthmax(200, 60 N) proposals, then restartannealing
Step cap (default)10,000,000 proposalsannealing
Greedy start tries4,096 random unused columns per rowmin-conflicts
Random rows before a full scan4,000 tries, then one pass over all rowsmin-conflicts
Restart ruleNo new low in max(200, 20 N) repairsmin-conflicts
Benchmark capsTime cap of 5 to 120 s per run, by agent and size; backtracking also a 2,000,000-step capbenchmark
Benchmark seedsFrom 1000; trial i uses seed 1000 + i for every agentbenchmark
Server time budget2.0 s of CPU per requestserver
Largest N servedBacktracking 64; hill climbing 100; annealing 2,000; min-conflicts 10,000server

The values are constants in the agent module39, the benchmark plan40, the server limits41, and the browser copies of the greedy and repair constants42.

How these were chosen: The annealing temperatures (2.0 down to 0.05) and run length (60 N, with a floor of 200) are fixed choices, not tuned. Cooling is geometric, so every run spends the same factor of temperature. The greedy start's 4,096 tries and the rejection threshold of 4,000 favour speed. The restart rule max(200, 20 N) is also a fixed choice. The server's caps are the sizes past which a request would only reach its time cap or use most of the shared CPU budget. They are not benchmark results. No parameter sweep is committed for any agent.

Results on fixed seeds

NBacktrackingHill climbingAnnealingMin-conflicts
81 of 1 solved, 218 steps200 of 200, 22 steps200 of 200, 778 steps200 of 200, 24 steps
161 of 1, 20,088 steps100 of 100, 170 steps100 of 100, 13,420 steps200 of 200, 44 steps
320 of 1 (step cap)30 of 30, 1,024 steps30 of 30, 712,202 steps100 of 100, 44 steps
1280 of 1 (step cap)0 of 3 (time cap)0 of 5 (time cap)100 of 100, 52 steps
1,0000 of 1 (step cap)0 of 2 (time cap)0 of 3 (time cap)50 of 50, 54 steps
10,0000 of 1 (step cap)not run0 of 2 (step cap)20 of 20, 56 steps
100,000not runnot runnot run3 of 3, 116 steps
1,000,000not runnot runnot run1 of 1, 47 steps (13.6 s)

The table is the committed benchmark, with seeds from 1000 on3843. Steps are each agent's own unit: placements and retreats for backtracking, moves played for hill climbing (restarts included), proposals for annealing, and repairs for min-conflicts. The shared work measure is candidate squares scored. At 16 queens the medians are 10,052 for backtracking, 43,392 for hill climbing, 13,420 for annealing and 9,976 for min-conflicts. Hill climbing at 10,000 queens was not run, because one step would score 108 squares. Medians are over solved runs.

The benchmark runs each case with a time cap, and a case that hits its cap is recorded as a failure with its reason44. Every reported solution is checked as a valid placement before it is counted.