Learn / Recursion and backtracking
N-Queens
Place one queen per row. For each row, try every column that no earlier queen attacks, recurse into the next row, and undo. Three boolean arrays (columns, the r + c diagonals and the r - c diagonals) check a square in O(1).
How to recognise it
- Items must be placed on a board so that no two clash, one per row or column.
- The question asks for all valid arrangements or how many there are.
The idea in one picture
Go down the board row by row. In each row, slide a queen along until it sits on a square no earlier queen can reach. Go to the next row. If a row has no safe square, step back to the previous row and slide that queen further.
Checking a square in O(1)
| Line | Same value along it | Array size |
|---|---|---|
| column | c | n |
| down-right diagonal | r - c (shift by n to keep it positive) | 2n |
| up-right diagonal | r + c | 2n |
Template
function place(r):
if r == n: record the board; return
for c from 0 to n - 1:
if col[c] or diag[r + c] or anti[r - c + n]: continue
mark all three; queen[r] = c
place(r + 1)
unmark all three
Common mistakes
- Checking only columns, or only one diagonal.
- Forgetting to unmark after the recursive call.
- Scanning the whole board to check a square, which is O(n) per check instead of O(1).
Problems
- N-Queenshardguide ready