The N-queens puzzle is a classic computer science problem that predates computer science. Given an N x N chessboard, the question asks the number of ways of placing N queens on the chessboard such that no queens attack any other queens. On a standard chessboard there are 92 solutions, of which 12 are rotationally invariant.
The N -queens puzzle (canonically, the 8 queens puzzle) is a famous and classic computer science problem due to its challenging nature, and its ability to be solved through the application of recursive backtracking. It is often used to introduce the concept of backtracking.
Background
The N-queens problem predates computers, and was first proposed and solved by chess players in the 19th century. The problem asks, given an N x N chessboard, how many unique ways are there of placing N queens on the board such that no queen attacks any other queen. The queen can travel vertically, horizontally, and diagonally, so as each queen is placed, the number of remaining legal positions becomes smaller and smaller.
Solution Procedure
A sensible recursive backtracking solution to the N-queens problem places one queen at a time, restricting the solution space considered for further queen placements only to legal positions (contrast with a brute force solution, which waits until all N queens have been placed to check if the placement of each queen is valid).
Variations
There are variations on the N queens problem - for example, the N rooks problem (placing N rooks on an N x N chessboard such that no rook attacks any other rook), which is a slightly less constrained version of the N queens problem, as rooks can attack vertically and horizontally, but not diagonally. There are other variations involving knights, bishops, and kings, but these pieces typically involve placing more than N pieces to keep the problem from becoming trivial.
Mathematicians and computer scientists have published diverse investigations into solving the N-queens puzzle in a variety of contexts: three dimensional chessboards, torroidal chessboards, and extremely large chessboards.
Useful Resources
Resources Explaining N-Queens Problem
- Wikipedia article on 8 queens puzzle
- N Queens Problem at Wolfram Mathworld - Gives a generating function polynomial for determining the solution as a function of N
- Integer Sequence A000170 at the Online Encyclopedia of Integer Sequences - The sequence of "Number of ways of placing n nonattacking queens on an N x N board" as N increases
N-Queens Solutions in Code
- 8 Queens Problem at Rosetta Code - Solutions to the N Queens problem in nearly 100 different programming languages
- Solving the N Queens Problem with Google's Operations Research optimization library
- Code Golf Stack Exchange: N Queens Puzzle - Extremely compactified solutions to the N Queens Puzzle in a variety of programming languages