N-Queens
Master this topic with zero to advance depth.
N-Queens
The Constraint Logic
The N-Queens puzzle is about placing chess queens on an chessboard so that no two queens threaten each other. A queen can attack in 3 ways: Row, Column, and Diagonal.
Efficient Collision Detection
Instead of checking every cell on the board (which is ), we can use boolean arrays to mark occupied lanes:
- Column: Index
c - Main Diagonal: Index
r - c(constant along the diagonal) - Anti-Diagonal: Index
r + c(constant along the diagonal)
Place N queens on an N x N board without conflicts. Includes visual 4-Queens solution.
Examples
Level I: Backtracking with Validation Function
Intuition
Place queens row by row. For each valid column in a row, move to the next row.
For each row r, try placing a queen at (r, c) where c from to . Check if (r, c) is safe by scanning all previously placed queens.
Detailed Dry Run
Dry Run: N=4
| Row | Action | Collision Check |
| :-- | :--------------- | :-------------- |
| 0 | Place (0,0) | Valid |
| 1 | Try (1,0), (1,1) | â Col/Diag |
| 1 | Place (1,2) | Valid |
| 2 | Try (2,0)..(2,3) | â ALL COLLIDE |
| 1 | Backtrack (1,2) | Try (1,3)... |Level II: Optimized Backtracking (Hashing O(1) Checks)
Intuition
Use boolean arrays/sets to track occupied columns and diagonals for immediate collision detection.
Maintain cols, diag1 (), and diag2 () sets. Before placing a queen at , check if , , or are in the sets.
Detailed Dry Run
Place (0,0): cols={0}, d1={0}, d2={0} Row 1: (1,1) fails (d1), (1,2) ok (c=2, d1=-1, d2=3).
Level III: Bit Manipulation (Ultimate Speed)
Intuition
Use integers as bitmasks to represent occupied columns and diagonals. This is the fastest way because bitwise operations are extremely cheap.
Let cols, ld (left-diagonal), and rd (right-diagonal) be integers. For each row, the available slots are ~(cols | ld | rd) & mask. Placing a queen update masks: cols | p, (ld | p) << 1, (rd | p) >> 1.
Detailed Dry Run
N=4, mask=1111 Row 0: Try p=0001. New cols=0001, ld=0010, rd=0000 Row 1: Try p=0100...
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.