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.
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 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.
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.
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 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.
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.
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.
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
function BACKTRACK(n):
full ← 2^n − 1 # bit c stands for column c
C[0] ← 0; L[0] ← 0; R[0] ← 0 # nothing is taken above row 0
open[0] ← full
row ← 0
steps ← 0; nodes ← 0 # steps: placements and retreats
placed ← [−1, …, −1] # −1 marks an empty row
while row < n:
bits ← open[row]
if bits = 0: # dead end: no open column in this row
if row = 0:
stop: "exhausted" # no solution exists
row ← row − 1 # retreat to the row above
placed[row] ← −1
steps ← steps + 1
else:
bit ← bits AND (−bits) # lowest open column
open[row] ← bits XOR bit # this column is not tried again
placed[row] ← column of bit
c ← C[row] OR bit
ld ← ((L[row] OR bit) << 1) AND full
rd ← (R[row] OR bit) >> 1
row ← row + 1
C[row] ← c; L[row] ← ld; R[row] ← rd
open[row] ← full AND NOT (c OR ld OR rd)
steps ← steps + 1
nodes ← nodes + 1 # the work measure: placements
if max_steps is set and steps ≥ max_steps:
stop: "step cap"
if steps mod 256 = 0 and the time limit has passed:
stop: "time cap"
return placed # complete only if row = n
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.
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.
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.
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
function HILL-CLIMB(n, max_steps, max_restarts, time_limit):
board ← RANDOM-PLACEMENT(n)
steps ← 0; evals ← 0; restarts ← 0
while conflicts(board) > 0:
if max_steps is set and steps ≥ max_steps:
stop: "step cap"
if the time limit has passed:
stop: "time cap"
best_d ← 0; best ← empty list
for each row r:
cur ← column of the row-r queen
base ← col[cur] + d1[r + cur] + d2[r − cur + n − 1] − 3 # attacks on that queen
for each column c with c ≠ cur:
d ← col[c] + d1[r + c] + d2[r − c + n − 1] − base # change in conflicts
if d < best_d:
best_d ← d; best ← [(r, c)]
else if d = best_d and d < 0:
append (r, c) to best
evals ← evals + n · n
if best is not empty:
(r, c) ← a move from best, chosen at random
MOVE(board, r, c)
else:
restarts ← restarts + 1
if max_restarts is set and restarts > max_restarts:
stop: "restart cap"
board ← RANDOM-PLACEMENT(n)
steps ← steps + 1
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 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.
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.
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.
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
function ANNEAL(n, max_steps, run_length, t0 = 2.0, t1 = 0.05, time_limit):
board ← RANDOM-PLACEMENT(n)
run_length ← max(200, 60 · n) # used when no length is given
cool ← (t1 / t0) ^ (1 / run_length)
steps ← 0; evals ← 0; restarts ← 0
temp ← t0; run_pos ← 0
while conflicts(board) > 0:
if max_steps is set and steps ≥ max_steps:
stop: "step cap"
if steps mod 1024 = 0 and the time limit has passed:
stop: "time cap"
if run_pos = run_length: # the run is over: start a new one
restarts ← restarts + 1
board ← RANDOM-PLACEMENT(n)
temp ← t0; run_pos ← 0
continue
r ← a random row
cur ← column of the row-r queen
c ← (cur + 1 + a random integer in [0, n − 2]) mod n # the other n − 1 columns
d ← attacks_if(r, c) − queen_attacks(r) # change in conflicts
if d ≤ 0 or a random number in [0, 1) < exp(−d / temp):
MOVE(board, r, c)
evals ← evals + 1
steps ← steps + 1
run_pos ← run_pos + 1
temp ← temp × cool
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 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.
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.
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.
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.
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
function MIN-CONFLICTS(n, max_steps, time_limit):
lines, cols, conflicts, evals ← GREEDY-START(n)
steps ← 0; restarts ← 0
best_seen ← conflicts; stall ← 0
stall_limit ← max(200, 20 · n)
while conflicts > 0:
if max_steps is set and steps ≥ max_steps:
stop: "step cap"
if steps mod 128 = 0 and the time limit has passed:
stop: "time cap"
if stall > stall_limit: # plateau: start again
restarts ← restarts + 1
lines, cols, conflicts, added ← GREEDY-START(n)
evals ← evals + added
best_seen ← conflicts; stall ← 0
continue
r ← −1
repeat up to 4000 times: # random rows first
cand ← a random row
if col[cols[cand]] + d1[cand + cols[cand]] + d2[cand − cols[cand] + n − 1] > 3:
r ← cand
break
if r < 0: # the random tries missed: list every row
bad ← every row whose queen is in conflict
r ← a random element of bad
old ← cols[r]
conflicts ← conflicts − (col[old] + d1[r + old] + d2[r − old + n − 1]) # lift the queen
for each column c:
score[c] ← col[c] + d1[r + c] + d2[r − c + n − 1]
best ← the smallest value in score
new_c ← a column c with score[c] = best, chosen at random
conflicts ← conflicts + score[new_c] # place the queen
cols[r] ← new_c
evals ← evals + n
steps ← steps + 1
if conflicts < best_seen:
best_seen ← conflicts; stall ← 0
else:
stall ← stall + 1
return cols
function GREEDY-START(n):
free ← every column; conflicts ← 0
for each row r from 0 to n − 1:
best_c ← −1; best_a ← infinity
repeat up to 4096 times: # random unused columns
c ← a random element of free
a ← d1[r + c] + d2[r − c + n − 1] # unused column: col[c] = 0
if a < best_a:
best_c ← c; best_a ← a
if a = 0:
break
remove best_c from free
conflicts ← conflicts + col[best_c] + d1[r + best_c] + d2[r − best_c + n − 1]
place the row-r queen on best_c and update the counts
return lines, cols, conflicts
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.
| Parameter | Value | Used by |
|---|---|---|
| Queens per row | Exactly 1 (conflicts are columns and diagonals only) | all |
| Column order | Lowest open column first | backtracking |
| Move choice | Best move; ties at random; no sideways moves; restart at a local minimum | hill climbing |
| Start and end temperature | T0 = 2.0, T1 = 0.05, geometric cooling | annealing |
| Run length | max(200, 60 N) proposals, then restart | annealing |
| Step cap (default) | 10,000,000 proposals | annealing |
| Greedy start tries | 4,096 random unused columns per row | min-conflicts |
| Random rows before a full scan | 4,000 tries, then one pass over all rows | min-conflicts |
| Restart rule | No new low in max(200, 20 N) repairs | min-conflicts |
| Benchmark caps | Time cap of 5 to 120 s per run, by agent and size; backtracking also a 2,000,000-step cap | benchmark |
| Benchmark seeds | From 1000; trial i uses seed 1000 + i for every agent | benchmark |
| Server time budget | 2.0 s of CPU per request | server |
| Largest N served | Backtracking 64; hill climbing 100; annealing 2,000; min-conflicts 10,000 | server |
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.
| N | Backtracking | Hill climbing | Annealing | Min-conflicts |
|---|---|---|---|---|
| 8 | 1 of 1 solved, 218 steps | 200 of 200, 22 steps | 200 of 200, 778 steps | 200 of 200, 24 steps |
| 16 | 1 of 1, 20,088 steps | 100 of 100, 170 steps | 100 of 100, 13,420 steps | 200 of 200, 44 steps |
| 32 | 0 of 1 (step cap) | 30 of 30, 1,024 steps | 30 of 30, 712,202 steps | 100 of 100, 44 steps |
| 128 | 0 of 1 (step cap) | 0 of 3 (time cap) | 0 of 5 (time cap) | 100 of 100, 52 steps |
| 1,000 | 0 of 1 (step cap) | 0 of 2 (time cap) | 0 of 3 (time cap) | 50 of 50, 54 steps |
| 10,000 | 0 of 1 (step cap) | not run | 0 of 2 (step cap) | 20 of 20, 56 steps |
| 100,000 | not run | not run | not run | 3 of 3, 116 steps |
| 1,000,000 | not run | not run | not run | 1 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.