Core Module
12 min forge
N-Queens Problem
Solve the legendary chessboard puzzle using backtracking. Learn how to manage 2D constraints on a 1D state.
π The N-Queens Problem
The N-Queens puzzle is the problem of placing $N$ chess queens on an $N \times N$ chessboard so that no two queens threaten each other. This is the "Godfather" of backtracking problems.
π‘ The Logic (ELI5)
Think of Jealous Socialites:
- You have a party with $N$ socialites (Queens) and $N$ tables.
- Every socialite wants their own row, their own column, and their own diagonal. They refuse to share!
- You place socialite 1 in the first column.
- Then you try a spot for socialite 2. If she's "threatened" by socialite 1, she complains! You have to move her.
- If you run out of spots for socialite 2, it means socialite 1 was in the wrong place! You have to go back and move socialite 1.
π The Deep Dive
Constraints
A queen at (r, c) threatens:
- Every cell in row
r. (Solved by placing only 1 queen per row). - Every cell in column
c. - Every cell on the Positive Diagonal (
r + cis constant). - Every cell on the Negative Diagonal (
r - cis constant).
Optimization ($O(1)$ Checks)
Instead of scanning the whole board to check if a spot is safe, keep Sets for columns and diagonals.
- Cols:
Setof $c$ indices. - Positive Diagonals:
Setof $r + c$. - Negative Diagonals:
Setof $r - c$.
π οΈ Code Forge: N-Queens Solver
javascript Standard/** * N-Queens Count Solver */ function totalNQueens(n) { let solutions = 0; const cols = new Set(); const posDiag = new Set(); // (r + c) const negDiag = new Set(); // (r - c) function backtrack(r) { if (r === n) { solutions++; return; } for (let c = 0; c < n; c++) { if (cols.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { continue; } // 1. PLACE cols.add(c); posDiag.add(r + c); negDiag.add(r - c); // 2. RECURSE backtrack(r + 1); // 3. REMOVE (BACKTRACK) cols.delete(c); posDiag.delete(r + c); negDiag.delete(r - c); } } backtrack(0); return solutions; } console.log(totalNQueens(4)); // Output: 2
π― Interview Pulse
Complexity
- Time: $O(N!)$. We try $N$ spots for the first row, $N-2$ for the second, etc.
- Space: $O(N)$ to store the sets and recursion stack.
Key Observation
The board itself is rarely needed in the calculation! You can solve the problem just by tracking the restricted indices.
Related Problems
- Sudoku Solver: A more complex 2D backtracking grid.
- Word Search: Navigating a 2D grid of characters.
- Knightβs Tour: Visiting every square on a chessboard exactly once.