N-Queens (backtracking)
Hard TimeO(n!) worst case SpaceO(n) board + stack
A queen attacks along its row, its column and both diagonals. Place n of them on an n × n board so that no two share a row, a column or a diagonal, and return one entry per solution giving the column chosen for each row. Exactly n queens are placed, one per row, and every solution is wanted rather than just the first.
Examples
Example 1
- Input
- n = 4
- Output
- Two solutions on a 4 × 4 board, each the mirror image of the other.
[[1,3,0,2],[2,0,3,1]]
Example 2
- Input
- n = 3
- Output
- Three queens cannot be placed on a 3 × 3 board at all, so there is no solution to return.
[]
The Code
function isSafe(cols, row, col) {
for (let r = 0; r < row; r++) {
if (cols[r] === col || Math.abs(cols[r] - col) === row - r) return false;
}
return true;
}
function place(cols, row, n, solutions) {
if (row === n) {
solutions.push(cols.slice());
return;
}
for (let col = 0; col < n; col++) {
if (isSafe(cols, row, col)) {
cols.push(col);
place(cols, row + 1, n, solutions);
cols.pop();
}
}
}
function solveNQueens(n) {
const solutions = [];
place([], 0, n, solutions);
return solutions;
}
solveNQueens(4);Done
The first 42 calls, of 293. This one does not fit on a page.
More like this
All backtracking examples (10) →- Permutations Fix each element first, then permute what remains.
- Subsets Every subset either includes the first element or it doesn’t.
- Combinations For each number, choose it or skip it (Pascal’s recurrence).
- Gen parentheses Add “(” while you can, “)” only when it stays balanced.
- Combination sum Reuse candidates freely; prune the moment the remainder goes negative.
- Palindrome partition Cut off every palindromic prefix, then partition the rest.