N-queens backtracking

Place N queens on an N × N board so that no two attack each other. Backtracking does it one row at a time, skipping attacked squares and stepping back from dead ends; min-conflicts drops every queen on the board and repairs. Watch both and count the work.

Queens placed
1
Backtracks
0
Solutions
0
Board
Method
Speed
Step 1 of 982
♛

attacked by a queen already placedtried and attackedbacktracking from here

Row 1: column 1 is safe, place a queen and go to the next row.

Search so far
Queens placed (tree nodes)
1
Squares skipped as attacked
0
Backtracks
0
Solutions found
0
Ways with no pruning (NN)
16,777,216

How to use the simulator

Pick a board size and a method and press Play. In backtracking the board shows the queens placed so far, shades every square they attack, and marks the square being tried. The counters on the right count every placement, skip and backtrack.

  • On 8 queens, step through the first solution. Notice how often a row turns out to have no safe square, and the search unwinds.
  • Switch to all solutions and run to the end: every one of the 92 solutions is found by the same procedure, carried on after each success.
  • Try min-conflicts on 12 queens: all queens start on the board and a handful of moves repair it.

The search code is checked against the known solution counts (OEIS A000170) for boards of 1 to 14, and every solution it reports is verified.

The N-queens problem

The N-queens problem asks for a way to place N chess queens on an N × N board so that no two share a row, a column or a diagonal. Since every row must hold exactly one queen, a solution is a list of N column numbers, one per row, with no column repeated and no two queens on a diagonal. Solutions exist for every N except 2 and 3.

It is a standard example of a constraint satisfaction problem and the usual first exercise in backtracking search.

Backtracking

Backtracking builds a solution one decision at a time and abandons a partial solution as soon as it cannot be completed. For N-queens:

  1. In the current row, take the leftmost column not attacked by any queen above.
  2. If there is one, place a queen and move to the next row; if all N rows are filled, record a solution.
  3. If there is none, go back to the previous row, remove its queen and try its next column.

Checking whether a square is attacked is constant time with three arrays of flags: used columns, used diagonals (row + column) and used anti-diagonals (row − column). Fast implementations keep the same information in three bitmasks and find all safe columns of a row with a few bitwise operations.

How big the search is

Queens placed by backtracking (the nodes of its search tree), compared with the NN arrangements a search without pruning would examine:

NSolutionsPlacements, first solutionPlacements, all solutionsUsing mirror symmetryNN
428168256
510553313,125
64311527646,656
7409551315823,543
8921132,0561,02816,777,216
9352418,3934,703387,420,489
1072410235,53817,7691.00 × 10^10
112,68052166,92591,3922.85 × 10^11
1214,200261856,188428,0948.92 × 10^12
1373,7121114,674,8892,531,7283.03 × 10^14
14365,5961,89927,358,55213,679,2761.11 × 10^16

Pruning cuts the work by many orders of magnitude, yet the tree still grows exponentially. Mirror symmetry halves it: a solution reflected left to right is also a solution, so the first queen only needs to try the left half of its row. The number of solutions itself has been computed exactly only up to N = 27, by the Q27 Project in 2016 on FPGAs.

Min-conflicts repair

Steven Minton and colleagues showed in 1992 that for finding a single solution, repairing a complete assignment beats building one. Place a queen in every row, for instance greedily so that each takes the least-attacked square given the rows above, then repeatedly pick a queen that is attacked and move it within its row to the square attacked by the fewest queens, breaking ties at random. Average moves to a solution in this simulator, over several runs:

NGreedy startRandom start
84433
504973
20029191
1,00059701

From a greedy start the number of moves barely grows with the board, which is what Minton's group reported for boards of up to a million queens. The method can stall on plateaus, which restarts handle, and it cannot count solutions or show that none exist; backtracking can.

Backtracking elsewhere

The same pattern of choose, check, recurse and undo solves Sudoku, graph colouring, subset sum, generating permutations and combinations, and parsing with regular expression engines that backtrack. SAT solvers are backtracking search with far stronger pruning: they propagate the consequences of each choice and learn new constraints from every dead end, which lets them handle problems with millions of variables.

History

The chess composer Max Bezzel published the eight queens puzzle in 1848, and Franz Nauck gave the first solutions in 1850 and generalized it to N queens; Carl Friedrich Gauss also worked on it. In computing, Niklaus Wirth used it to illustrate "Program development by stepwise refinement" in 1971, and Edsger Dijkstra used it in 1972 to illustrate structured programming with a depth-first backtracking algorithm. Minton, Johnston, Philips and Laird published min-conflicts in 1990 and in the journal Artificial Intelligence in 1992.

N-queens questions and answers

How does backtracking solve the N-queens problem?

It places one queen per row, trying columns from left to right and skipping any square attacked by a queen already placed. If a row has no safe square, it removes the queen in the row above and tries that queen's next column. For 8 queens it places queens 113 times before reaching the first solution, and 2,056 times to find all 92.

How many solutions does the 8 queens puzzle have?

92. Counting rotations and reflections of the board as the same, there are 12 fundamentally different solutions. The count grows quickly: 365,596 for 14 queens, and the largest board counted exactly so far is 27 × 27.

What is the time complexity of N-queens backtracking?

Exponential. The search tree is far smaller than the N^N ways to put one queen in each row, because attacked squares are pruned at once, but it still grows by a factor of about five or six per added row in this range: 27,358,552 placements for N = 14. No polynomial algorithm for counting the solutions is known.

How can very large N-queens boards be solved?

With local search instead of a tree search. The min-conflicts heuristic places all queens at once, then repeatedly moves an attacked queen to the square in its row that is attacked least. Starting from a greedy placement it solved a 1,000 × 1,000 board here in about 59 moves on average. It finds one solution quickly but cannot count solutions or prove there are none.

How does symmetry speed up counting solutions?

A solution reflected left to right is another solution, so it is enough to try the first row's queen in the left half of the columns and double the count, handling the middle column of an odd board separately. That halves the search. Using all eight symmetries of the square saves more, with extra bookkeeping for solutions that are symmetric themselves.

Why is N-queens used to teach backtracking?

It is easy to state, the constraints are simple to check, and pruning makes an enormous difference that is easy to see. Niklaus Wirth used it in 1971 in "Program development by stepwise refinement", and Edsger Dijkstra in 1972 in his notes on structured programming.

Further reading

Published Updated