Intermediate Topic 30 of 51 Algorithms
N-Queens Problem
Placing queens on a board so none attack each other.
How it works
The N-Queens problem asks for a placement of N queens on an N by N chessboard so that no two attack each other, meaning no two share a row, column or diagonal. A backtracking solution places one queen per row and tests columns, using sets or bit masks for used columns and the two diagonal directions, abandoning rows where no safe column remains.
Step-by-step walkthrough
- Place one queen per row on a 4 by 4 board.
- Row 1 gets a queen in column 2.
- Row 2 can only use column 4.
- Row 3 has no safe column, so backtrack and move the row 2 queen.
- Eventually the layout columns 2 4 1 3 puts every queen safely.
Where it is used
It is a classic exercise for backtracking, constraint satisfaction and parallel search, and has been used to benchmark solvers. The number of solutions grows quickly, for example 92 for N equal to 8.
Common pitfall
Checking safety by scanning the whole board each time is slow; track columns and diagonals in constant time. Diagonal indexes are computed with row minus column and row plus column. Counting versus printing all solutions changes the memory needed. Exploit symmetry to halve the work.
Where it fits in the course
N-Queens Problem is topic 30 of 51 in Algorithms, rated Intermediate. It follows Backtracking. The next topic is Breadth-First Search.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is N-Queens Problem?
Where do people use N-Queens Problem?
What is the most common mistake with N-Queens Problem?
What should I learn before this topic?
How can I practice it?
Is N-Queens Problem hard to learn?
How long does it take to learn N-Queens Problem?
Which topics are related to N-Queens Problem?
What should I study after N-Queens Problem?
Related topics
- Backtracking (Algorithms)
- Breadth-First Search (Algorithms)
- Edit Distance (Algorithms)
- Depth-First Search (Algorithms)
- Consensus Problem (Distributed Systems & Cloud)
- ABA Problem (Concurrency & Parallelism)
- Halting Problem (Theory & Discrete Math)