DSA Notes
Master the N-Queens problem completely — problem definition, why queens attack each other, step-by-step backtracking solution, constraint checking using column and diagonal sets, optimized solution with bitmasks, counting total solutions, and visualizing the complete search tree.
Problem Statement
Place N queens on an N×N chessboard such that no two queens attack each other. A queen attacks all squares in the same row, same column, and both diagonals.
Solution 1 — Basic Backtracking
Output for 4-Queens:
Solution 2 — Optimized with Hash Sets: O(n!)
The is_safe function in Solution 1 takes O(n) time. Using sets for column and diagonal tracking makes it O(1):
Trace — 4-Queens Solution
| Board | 4×4, placing queens row by row |
| Row 0 | Try col 0 |
| Row 1: col 0 | same col, skip |
| col 1 | diag1: 1-1=0 already in diag1, skip |
| col 2 | 1-2=-1, 1+2=3 — SAFE! Place |
| Row 2: col 0 | col in cols, skip |
| col 1 | 2+1=3 in diag2, skip |
| col 2 | col in cols, skip |
| col 3 | 2-3=-1 in diag1, skip |
| No valid placement | BACKTRACK |
| Row 1: col 3 | 1-3=-2, 1+3=4 — SAFE! Place |
| Row 2: col 0 | col in cols, skip |
| col 1 | 2-1=1, 2+1=3 — SAFE! Place |
| Row 3: col 0 | col in cols, skip |
| col 1 | col in cols, skip |
| col 2 | 3-2=1 in diag1, skip |
| col 3 | col in cols, skip |
| Row 2: col 2 | 2-2=0 in diag1, skip |
| col 3 | col in cols, skip |
| Row 0: Try col 1 | leads to first solution: [1,3,0,2] |
Solution 3 — Count Only (Bitmask): O(n!) — Fastest
For large n, if you only need the count (not the boards), bitmasks are fastest:
def count_n_queens(n):
"""
Count N-Queens solutions using bitmasks.
Dramatically faster for large n because bitwise ops are single instructions.
Time: O(n!), but with much smaller constant than set-based approach.
"""
all_ones = (1 << n) - 1 # n bits set to 1 (all columns)
count = 0
def backtrack(cols, diag1, diag2):
nonlocal count
if cols == all_ones: # All columns filled → found a solution
count += 1
return
# Available positions: columns not blocked by any queen
available = all_ones & ~(cols | diag1 | diag2)
while available:
# Pick the rightmost available position
position = available & (-available) # Isolate lowest set bit
available &= available - 1 # Clear lowest set bit
backtrack(
cols | position,
(diag1 | position) << 1, # Diagonal shifts left as row increases
(diag2 | position) >> 1 # Anti-diagonal shifts right
)
backtrack(0, 0, 0)
return count
for n in range(1, 10):
print(f"{n}-Queens: {count_n_queens(n)} solutions")
# 1-Queens: 1
# 2-Queens: 0
# 3-Queens: 0
# 4-Queens: 2
# 5-Queens: 10
# 6-Queens: 4
# 7-Queens: 40
# 8-Queens: 92
# 9-Queens: 352N-Queens Solutions Table
| N | Solutions |
|---|---|
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 5 | 10 |
| 6 | 4 |
| 7 | 40 |
| 8 | 92 |
| 9 | 352 |
| 10 | 724 |
| 11 | 2,680 |
| 12 | 14,200 |
| 13 | 73,712 |
First Non-Attacking Queen Placement
Complexity Analysis
| Approach | Time | Space | Notes |
|---|---|---|---|
| Basic (O(n) conflict check) | O(n! × n) | O(n) | Slowest |
| Set-based (O(1) conflict check) | O(n!) | O(n) | Standard interview |
| Bitmask | O(n!) | O(n) | Fastest in practice |
All approaches are ultimately O(n!) because there are O(n!) possible permutations of queen column positions to check. The optimization is in the constant factor.
Summary
The N-Queens problem is the canonical backtracking problem because it has:
- One decision per step: Which column to place the queen in (for the current row)
- Clear validity check: No two queens can share column or diagonal
- Perfect undo semantics: Remove queen, remove from sets
- Effective pruning: O(1) conflict detection eliminates most branches early
The three approaches (basic, set-based, bitmask) demonstrate the progression from correct solution to optimized solution — a pattern applicable to all backtracking problems.
*Next Lesson: Rat in a Maze*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for N-Queens Problem — Complete Solution with Backtracking and Optimization.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, backtracking, queens, problem
Related Data Structures & Algorithms Topics