Loading content...
In 1848, German chess master Max Bezzel posed a seemingly simple puzzle: Can you place eight queens on a standard 8×8 chessboard such that no two queens threaten each other? What appeared to be a recreational chess problem would become one of the most studied problems in computer science—a perfect crystallization of systematic search, constraint satisfaction, and the elegant power of backtracking.
The N-Queens problem (generalizing to any N×N board) stands as the canonical example of backtracking algorithms. It's the problem that textbooks reach for first, that interviewers ask to test recursive thinking, and that researchers use to benchmark constraint solvers. Understanding N-Queens deeply means understanding backtracking itself.
By the end of this module, you will understand the N-Queens problem from every angle: its formulation, solution strategies, constraint-checking optimizations, and variations. You'll implement efficient solutions, analyze their complexity, and recognize how the patterns here apply to countless other constraint satisfaction problems.
Before diving into algorithms, we must precisely understand what we're solving. Ambiguity in problem formulation leads to incorrect solutions, so let's establish crystal-clear definitions.
Given: An N×N chessboard.
Goal: Place exactly N queens on the board such that no two queens attack each other.
Constraint: In chess, a queen can attack any piece in the same row, column, or diagonal.
Understanding Queen Movement:
A queen combines the power of a rook (horizontal and vertical movement) and a bishop (diagonal movement). From any position, a queen can move:
This means if we place a queen at position (r, c), every other queen must avoid:
Key Insight for Diagonal Detection:
Diagonals have a beautiful mathematical property that makes checking trivial:
row - col = constantrow + col = constantFor example, on an 8×8 board:
row - col = 0 (same main diagonal)row + col = 3 (same anti-diagonal)This mathematical property will be crucial for efficient constraint checking.
You might wonder: why does a chess puzzle command so much attention in computer science? The answer lies in what N-Queens represents, not merely what it solves.
Historical Significance:
The 8-Queens problem was first posed in 1848 and has attracted contributions from legendary mathematicians including Carl Friedrich Gauss, who worked on it in 1850. The problem has been solved using methods ranging from brute force to genetic algorithms, from constraint propagation to neural networks.
In 1874, S. Günther proved that solutions exist for all N ≥ 4 (N=2 and N=3 have no solutions). The exact formula for counting solutions remains unknown, making it computationally interesting even today.
| N (Board Size) | Number of Solutions | Distinct Solutions (Symmetry) | Notes |
|---|---|---|---|
| 1 | 1 | 1 | Trivial case |
| 2 | 0 | 0 | No solution exists |
| 3 | 0 | 0 | No solution exists |
| 4 | 2 | 1 | Smallest non-trivial case |
| 5 | 10 | 2 | — |
| 6 | 4 | 1 | — |
| 7 | 40 | 6 | — |
| 8 | 92 | 12 | Classic chessboard |
| 9 | 352 | 46 | — |
| 10 | 724 | 92 | — |
| 12 | 14200 | 1787 | — |
| 14 | 365596 | 45752 | Millions of nodes searched |
Notice how the solution count grows dramatically. The solution count for N=27 is over 234 billion! This exponential growth is why naive approaches fail and why intelligent search strategies matter.
To appreciate why backtracking is necessary, we must understand the search space—the set of all possible configurations we might consider.
Naive Approach: Brute Force Over All Placements
The most naive approach considers every possible way to place N queens on N² squares:
For an 8×8 board: C(64, 8) = 4,426,165,368 (over 4 billion configurations!)
Even at a million checks per second, this would take over an hour just for N=8. Clearly, brute force is not viable.
First Optimization: One Queen Per Row
Here's a critical insight: since no two queens can share a row, each row must contain exactly one queen. This transforms the problem:
For N=8: 8^8 = 16,777,216 (about 17 million)
This is already 250× better than brute force! But we can do even better.
Second Optimization: One Queen Per Column Too
Similarly, each column must contain exactly one queen. This means a valid placement is really a permutation: column assignments such that each column appears exactly once.
For N=8: 8! = 40,320
This is another 400× improvement! We've reduced 4 billion to 40 thousand just by recognizing structure.
| Approach | Formula | Configurations | Improvement Factor |
|---|---|---|---|
| Brute force (any placement) | C(64, 8) | 4,426,165,368 | Baseline |
| One queen per row | 8^8 | 16,777,216 | 264× |
| One queen per row and column | 8! | 40,320 | 109,776× |
| With backtracking (typical) | ~2000 nodes | ~2,000 | ~2,213,000× |
By recognizing that the solution must be a permutation (one queen per row AND per column), we've already reduced the search space by a factor of 100,000. Backtracking will take us even further by pruning partial solutions that violate diagonal constraints.
N-Queens exhibits all the properties that make a problem ideal for backtracking. Let's examine each one:
The Backtracking Mental Model:
Think of backtracking as exploring a decision tree:
Backtracking traverses this tree depth-first, pruning branches the moment a constraint violation is detected. This pruning is what makes it efficient.
Key Observation:
In the tree above (for 4-Queens), notice how entire subtrees are pruned when we detect a conflict. The branch starting with Q at (0,0) → Q at (1,2) leads nowhere because row 2 has no valid column. We don't explore any of those grandchildren—we immediately backtrack.
This pruning is what takes us from 40,320 permutations (8!) down to roughly 2,000 nodes visited for solving 8-Queens. That's a 95% reduction in explored configurations!
Let's solve the smallest non-trivial case by hand to internalize the backtracking process. We'll place queens row by row, tracking columns and diagonals carefully.
We'll denote queen positions as (row, column), both 0-indexed. The board is:
0 1 2 3
0 [ ] [ ] [ ] [ ]
1 [ ] [ ] [ ] [ ]
2 [ ] [ ] [ ] [ ]
3 [ ] [ ] [ ] [ ]
Step 1: Place first queen
We try column 0 in row 0. No conflicts possible—it's our first queen.
0 1 2 3
0 [♛] [ ] [ ] [ ] ← Queen at (0,0)
1 [ ] [ ] [ ] [ ]
2 [ ] [ ] [ ] [ ]
3 [ ] [ ] [ ] [ ]
Attacked zones: Column 0, Row 0, diagonals (r-c=0) and (r+c=0)
Step 2: Place second queen in row 1
0 1 2 3
0 [♛] [ ] [×] [×] × = attacked by Q at row 0
1 [×] [×] [♛] [ ] ← Queen at (1,2)
2 [ ] [×] [×] [×]
3 [ ] [ ] [×] [ ]
Notice how backtracking saved us from exhaustively checking all 4! = 24 permutations. We pruned branches early when conflicts were detected, visiting far fewer states than a generate-and-test approach would require.
The N-Queens problem comes in several flavors, each with different algorithmic implications:
Add return true after finding first solution. Time complexity: O(N!) worst case, but typically much faster due to early termination.
Continue searching after finding each solution. Record, then backtrack to find more. Must exhaustively search entire tree.
Interview Tip:
Interviewers often start with 'find one solution' to test basic backtracking, then ask 'find all solutions' as a follow-up. The key difference is what happens after finding a valid placement: do you return immediately or continue searching?
Understanding both variants and their tradeoffs demonstrates mastery of the problem.
We'll analyze complexity in detail later, but here's a preview of what to expect:
Time Complexity:
Space Complexity:
Despite optimizations, N-Queens fundamentally has exponential solution counts. For N=27, there are over 234 billion solutions. No algorithm can enumerate all of them quickly. This is why the problem remains interesting for testing heuristics, parallel algorithms, and constraint satisfaction techniques.
We've established the foundation for understanding N-Queens as the canonical backtracking problem:
What's Next:
With the problem clearly defined, we'll now dive into the mechanics of queen placement. The next page covers how to systematically build valid placements, handle state management, and implement the core backtracking loop.
You now understand N-Queens as the quintessential backtracking problem. You can explain the problem, recognize why backtracking is the natural approach, and understand the solution space structure. Next, we'll implement the solution step by step.