This puzzle was used in the popular early 1990s computer game, The 7th Guest[?]. However, it has a rich history predating this game; the generalized problem of placing n "nondominating" queens on an n by n chessboard was posed as early as 1850.
The eight queens problem has 92 distinct solutions, or 12 distinct solutions if symmetry operations such as rotations and reflections of the board are taken into consideration.
The eight queens puzzle is a good example of a simple but nontrivial problem that can be solved by a recursive algorithm, by phrasing the nqueen problem inductively in terms of adding a single queen to any solution to the (n1)queen problem. The induction bottoms out with the solution to the 0queen problem, which is an empty chessboard.
This technique is much more efficient than the naive bruteforce algorithm, which considers all 64^{8} possible blind placements of eight queens, and then filters these to remove all placements that place two queens either on the same square or in mutually attacking positions. This very poor algorithm will, amongst 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 subsets of each solution. A slightly better bruteforce algorithm places a single queen on each row, leading to only 8^{8} blind placements.
It is often used as an example problem for nontraditional approaches, such as constraint programming, logic programming or genetic algorithms.
This uses the insights that
# Return a list of solutions to the nqueens problem on an # nbywidth 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(n1, width, n_queens(n1, 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_rowqueens # 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 iff so. sol must be a solution to the new_rowqueens 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 sol[row] + row == new_col + new_row or sol[row]  row == new_col  new_row): return 0 return 1
for sol in n_queens(8, 8): print sol
See also:
External links to solutions using:
Other external links:
Search Encyclopedia

Featured Article
