# Xkcd

*224,339*pages on

this wiki

Welcome to the **Xkcd** mini wiki at **Scratchpad!**

You can use the box below to create new pages for this mini-wiki. Make sure you type ** [[Category:Xkcd]]** on the page before you save it to make it part of the Xkcd wiki (preload can be enabled to automate this task, by clicking this link and saving that page. Afterwards, you may need to purge this page, if you still see this message).

| ||

Difficulty:
| Hard | |

Categories:
| Math, Solved | |

Submitted by:
| xkcd
| |

Solved by:
| xkcd
| |

Status:
| Solved |

All content after this is not my own, but is used as an example of an extremely in depth puzzle solving page. Taken from [[1]]

The **eight queens puzzle** is the problem of putting eight chess queens on an 8×8 chessboard such that none of them is able to capture any other using the standard chess queen's moves. The colour of the queens is meaningless in this puzzle, and any queen is assumed to be able to attack any other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general ** n queens puzzle** of placing

*n*queens on an

*n*×

*n*chessboard.

## History

The puzzle was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss and Georg Cantor, have worked on this puzzle and its generalized n-queens problem. The first solutions were provided by Franz Nauck in 1850. Nauck also extended the puzzle to n-queens problem. In 1874, S. Gunther proposed a method of finding solutions by using determinants, and J.W.L. Glaisher refined this approach.

This puzzle appeared in the popular early 1990s computer game *The 7th Guest*.

## Constructing a solution

There is a simple algorithm yielding a solution to the *n* queens puzzle for *n* = 1 or any *n* ≥ 4:

- Divide
*n*by 12. Remember the remainder (it's 8 for the eight queens puzzle). - Write a list of the even numbers from 2 to
*n*in order. - If the remainder is 3 or 9, move 2 to the end of the list.
- Write the odd numbers from 1 to
*n*in order, but, if the remainder is 8, switch pairs (i.e. 3, 1, 7, 5, 11, 9, …). - If the remainder is 2, switch the places of 1 and 3, then move 5 to the end of the list.
- If the remainder is 3 or 9, move 1 and 3 to the end of the list.
- Place the first-column queen in the row with the first number in the list, place the second-column queen in the row with the second number in the list, etc.

For *n* = 8 this results in the solution shown above. A few more examples follow.

- 14 queens (remainder 2): 2, 4, 6, 8, 10, 12, 14, 3, 1, 7, 9, 11, 13, 5.
- 15 queens (remainder 3): 4, 6, 8, 10, 12, 14, 2, 5, 7, 9, 11, 13, 15, 1, 3.
- 20 queens (remainder 8): 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 1, 7, 5, 11, 9, 15, 13, 19, 17.

## Solutions to the eight queens puzzle

The eight queens puzzle has 92 **distinct** solutions. If solutions that differ only by symmetry operations (rotations and reflections) of the board are counted as one, the puzzle has 12 **unique** solutions, which are presented below:

## Counting solutions

The following table gives the number of solutions for *n* queens, both unique Template:OEIS and distinct Template:OEIS.

n:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | .. | 23 | 24 | 25 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

unique: | 1 | 0 | 0 | 1 | 2 | 1 | 6 | 12 | 46 | 92 | 341 | 1,787 | 9,233 | 45,752 | 285,053 | .. | 3,029,242,658,210 | ? | ? |

distinct: | 1 | 0 | 0 | 2 | 10 | 4 | 40 | 92 | 352 | 724 | 2,680 | 14,200 | 73,712 | 365,596 | 2,279,184 | .. | 24,233,937,684,440 | 227,514,171,973,736 | 2,207,893,435,808,352 |

Note that the 6 queens puzzle has fewer solutions than the 5 queens puzzle.

## Related problems

- Using pieces other than queens
- For example, on an 8×8 board one can place 32 knights, or 14 bishops, or 16 kings, so that no two pieces attack each other. Fairy chess pieces have also been substituted for queens. In the case of knights, an easy solution is to place one on each square of a given color, since they move only to the opposite color.
- Nonstandard boards
- Pólya studied the
*n*queens problem on a toroidal ("donut-shaped") board. Other shapes, including three-dimensional boards, have also been studied. - Domination
- Given an
*n*×*n*board, find the**domination number**, which is the minimum number of queens (or other pieces) needed to attack or occupy every square. For the 8×8 board, the queen's domination number is 5. - Nine queens problem
- Place nine queens and one pawn on an 8×8 board in such a way that queens don't attack each other. Further generalization of the problem (complete solution is currently unknown): given an
*n*×*n*chess board and*m*>*n*queens, find the minimum number of pawns, so that the*m*queens and the pawns can be set up on the board in such a way that no two queens attack each other. - Queens and knights problem
- Place m queens and m knights on an n by n board such that no piece attacks another.
- Magic squares
- In 1992, Demirörs, Rafraf, and Tanik published a method for converting some magic squares into
*n*queens solutions, and vice versa. - Latin squares
- In an
*n*×*n*matrix, place each digit 1 through*n*in*n*locations in the matrix such that no two instances of the same digit are in the same row or column. - Exact cover
- Consider a matrix with one primary column for each of the
*n*ranks of the board, one primary column for each of the*n*files, and one secondary column for each of the 4*n*-6 nontrivial diagonals of the board. The matrix has*n*^{2}rows: one for each possible queen placement, and each row has a 1 in the columns corresponding to that square's rank, file, and diagonals and a 0 in all the other columns. Then the*n*queens problem is equivalent to choosing a subset of the rows of this matrix such that every primary column has a 1 in precisely one of the chosen rows and every secondary column has a 1 in at most one of the chosen rows; this is an example of a generalized exact cover problem, of which sudoku is another example.

## The eight queens puzzle as an exercise in algorithm design

Finding all solutions to the eight queens puzzle is a good example of a simple but nontrivial problem. For this reason, it is often used as an example problem for various programming techniques, including nontraditional approaches such as constraint programming, logic programming or genetic algorithms. Most often, it is used as an example of a problem which can be solved with a recursive algorithm, by phrasing the *n* queens problem inductively in terms of adding a single queen to any solution to the problem of placing *n*−1 queens on an n-by-n chessboard. The induction bottoms out with the solution to the 'problem' of placing 0 queens on an n-by-n chessboard, which is the empty chessboard.

This technique is much more efficient than the naïve brute-force search algorithm, which considers all 64^{8} = 2^{48} = 281,474,976,710,656 possible blind placements of eight queens, and then filters these to remove all placements that place two queens either on the same square (leaving only 64!/56! = 178,462,987,637,760 possible placements) or in mutually attacking positions. This very poor algorithm will, among other things, produce the same results over and over again in all the different permutations of the assignments of the eight queens, as well as repeating the same computations over and over again for the different sub-sets of each solution. A better brute-force algorithm places a single queen on each row, leading to only 8^{8} = 2^{24} = 16,777,216 blind placements.

It is possible to do much better than this. One algorithm generates the permutations of the numbers 1 through 8 (of which there are 8! = 40,320), uses the elements of each permutation as indices to place a queen on each row, guaranteeing no rook attacks. Then it rejects those boards with diagonal attacking positions. The breadth-first search program below, a slight improvement on the permutation method, constructs the search tree by considering one row of the board at a time, eliminating most nonsolution board positions at a very early stage in their construction. Because it rejects diagonal attacks even on incomplete boards, it examines only 15,720 possible queen placements.

Constraint programming is even more effective on this problem. An 'iterative repair' algorithm typically starts with all queens on the board, for example with one queen per column. It then counts the number of conflicts (attacks), and uses a heuristic to determine how to improve the placement of the queens.

The 'minimum-conflicts' heuristic — moving the piece with the largest number of conflicts to the square in the same column where the number of conflicts is smallest — is particularly effective: it solves the 1,000,000 queen problem in less than 50 steps on average. This assumes that the initial configuration is 'reasonably good' — if a million queens all start in the same row, it will obviously take at least 999,999 steps to fix it. A 'reasonably good' starting point can for instance be found by putting each queen in its own row and column such that it conflicts with the smallest number of queens already on the board.

Note that 'iterative repair', unlike the 'breadth-first' search outlined above, does not guarantee a solution: like all hillclimbing procedures, it may get stuck on a local optimum (in which case the algorithm may be restarted with a different initial configuration). On the other hand, it can solve problem sizes that are several orders of magnitude beyond the scope of a breadth-first search.

## An animated version of the recursive solution

This animation uses backtracking to solve the problem. A queen is placed in a column that is known not to cause conflict. If a column is not found the program returns to the last good state and then tries a different column.

## A standard recursive solution

The Python functions below can generate all solutions for an *n*-queens problem, using a recursive breadth-first search combined with the hard-coded insights that :

- no two pieces can share the same row
- any solution for
*n*queens on an*n*×*m*board must contain a solution for*n*−1 queens on an (*n*−1)×*m*board - proceeding in this way will always keep the queens in order, and generate each solution only once.

# Return a list of solutions to the ''n''-queens problem on an # ''n''-by-width board. A solved board is expressed as a list of # column positions for queens, indexed by row. # Rows and columns are indexed from zero. def n_queens(n, width): if n == 0: return [[]] # one solution, the empty list else: return add_queen(n-1, width, n_queens(n-1, width)) # Try all ways of adding a queen to a column of row new_row, returning # a list of solutions. previous_solutions must be a list of new_row-queens # solutions. def add_queen(new_row, width, previous_solutions): solutions = [] for sol in previous_solutions: # Try to place a queen on each column on row new_row. for new_col in range(width): # print 'trying', new_col, 'on row', new_row if safe_queen(new_row, new_col, sol): # No interference, so add this solution to the list. solutions.append(sol + [new_col]) return solutions # Is it safe to add a queen to sol at (new_row, new_col)? Return # true if so. sol must be a solution to the new_row-queens problem. def safe_queen(new_row, new_col, sol): # Check against each piece on each of the new_row existing rows. for row in range(new_row): if (sol[row] == new_col or # same column clash sol[row] + row == new_col + new_row or # diagonal clash sol[row] - row == new_col - new_row): # other diagonal return 0 return 1 for sol in n_queens(8, 8): print sol

In C++:

#include <stdio.h> int row[8], s = 0; bool safe(int x, int y) { for (int i = 1; i <= y; i++) if (row[y - i] == x || row[y - i] == x - i || row[y - i] == x + i) return false; return true; } void putboard() { printf("\nSolution #%d:\n---------------------------------\n", ++s); for (int y = 0; y < 8; printf("|\n---------------------------------\n"), y++) for (int x = 0; x < 8; printf(x++ == row[y] ? "| Q " : "| ")); } int main(int y) { for (int x = 0; x < 8; x++) if (safe(row[y - 1] = x, y - 1)) if (y < 8) main(y + 1); else putboard(); }

## A constraint logic programming solution

The constraint logic programming (over finite domains) approach to this kind of problem is very efficient. The GNU Prolog program below resolved a 100-queens problem in less than a tenth of a second. It finds a permutation of the first *n* naturals such that the distance between any two is not the normal distance (for example, 1 is normally three away from 4).

```
```

```
```/* Generates a list which represents a single solution
with the specified length and ensures that the list has each value
from 1 to N once and only once. */
nqueens(N,Ls) :- length(Ls,N),
fd_domain(Ls,1,N),
fd_all_different(Ls),
constraint_queens(Ls),
fd_labeling(Ls,[variable_method(random)]).
/* Ensures that all positions are valid */
constraint_queens([]).
constraint_queens([X|Xs]) :- noattack(X,Xs,1), constraint_queens(Xs).
/* Ensures that no queens share diagonals */
noattack(_,[],_).
noattack(X,[Y|Xs],N) :- X#\=Y+N, X#\=Y-N, T=N+1, noattack(X,Xs,T).

```
```

## An iterative solution

The following J verb
generates all solutions for an *n*-queens problem, using an iterative approach.

queens=: 3 : 0 z=.i.n,*n=.y. for. }.z do. b=. -. (i.n) e."1 ,. z +"1 _ ((-i.){:$z) */ _1 0 1 z=. ((+/"1 b)#z),.(,b)#(*/$b)$i.n end. )

A *k*-arrangement `x` has *k* queens on a *k*-by-*n* board where none of
queens attack each other. To generate all *k+1*-arrangements leading from `x`,
place a queen on all the places on row *k* which are not on the any of the columns or
diagonals attacked by the queens in `x`.
The *1*-arrangements are 0, 1, 2, ..., *n*-1; the *n*-arrangements are
all the solutions to the *n*-queens problem.

For example, 0 2, 0 3, and 0 4 are valid 2-arrangements for the 8-queens problem. The 3-arrangements leading from these are:

0 2 4 0 2 5 0 2 6 0 2 7 0 3 1 0 3 5 0 3 6 0 3 7 0 4 1 0 4 6 0 4 7

## See also

## References

- Watkins, John J. (2004).
*Across the Board: The Mathematics of Chess Problems*. Princeton: Princeton University Press. ISBN 0-691-11503-6.

## External links

- An Applet simulating the random-greedy solution for the n-queen problem
- MathWorld article
- Solutions to the 8-Queens Problem
- Walter Koster's N-Queens Page
- Durango Bill's N-Queens Page
- On-line Guide to Constraint Programming
- n-Queens in C++; Implementation & analysis of several heuristics to speed up solving the n-queens problem

### Links to solutions

- N-Queens solvers in many programming languages
- A Koalog Constraint Solver model
- Find your own solution
- J Somers N-Queen code
- Atari BASIC
- Genetic algorithms
- Haskell/Java hybrid
- Java
- Java
- Standard ML
- Integer Sequences
- Quirkasaurus' 8 Queens Solution
- LISP solution for N-Queens Problem
- javascript solution for 8-Queens Problem
- Brute-force solution for eight queens in a web based interactive classic BASIC environment
- Conflict heuristics solution for the eight queens in a web based interactive classic BASIC environment