N-Queens backtracking algorithm explained step-by-step: state space tree exploration, safe position checks via O(1) hash sets / bitmasks, diagonal indexing math, and JavaScript implementation.
The N-Queens Problem is the classic constraint satisfaction problem in computer science. The challenge is to place N non-attacking chess queens on an N × N chessboard so that no two queens share the same row, column, or diagonal.
A naive brute-force search over all (N²) choose N board combinations is computationally intractable. Backtracking solves this efficiently by placing queens row by row. Whenever a conflict is detected in a column or diagonal, the algorithm prunes that entire sub-tree immediately and backtracks to explore alternative placements.
Place exactly one queen per row, starting at row 0 and progressing down to row N - 1. This naturally prevents any two queens from sharing the same row.
Check if column `c`, main diagonal `(row - c)`, or anti-diagonal `(row + c)` are already occupied by previous queens. Constant difference `row - c` identifies \ diagonals, while constant sum `row + c` identifies / diagonals.
If the square is safe, mark column `c`, `row - c`, and `row + c` as occupied, record the queen position, and recursively call the backtrack solver for `row + 1`.
Upon returning from recursion (or if all columns in the current row are blocked), undo the placement: unmark column `c`, `row - c`, and `row + c`, remove the queen from the board, and try the next column.
1function solveNQueens(n) {2 const result = [];3 const cols = new Set();4 const diag1 = new Set(); // Major diagonal: row - col is constant5 const diag2 = new Set(); // Anti-diagonal: row + col is constant6 7 function backtrack(row, currentBoard) {8 // Base Case: All N queens safely placed9 if (row === n) {10 result.push([...currentBoard]);11 return;12 }13 14 for (let col = 0; col < n; col++) {15 const d1 = row - col;16 const d2 = row + col;17 18 // Skip if column or diagonals are under attack19 if (cols.has(col) || diag1.has(d1) || diag2.has(d2)) {20 continue;21 }22 23 // 1. Choose: Place Queen24 cols.add(col);25 diag1.add(d1);26 diag2.add(d2);27 const rowStr = '.'.repeat(col) + 'Q' + '.'.repeat(n - col - 1);28 currentBoard.push(rowStr);29 30 // 2. Explore: Recurse to next row31 backtrack(row + 1, currentBoard);32 33 // 3. Un-choose (Backtrack): Undo state34 currentBoard.pop();35 cols.delete(col);36 diag1.delete(d1);37 diag2.delete(d2);38 }39 }40 41 backtrack(0, []);42 return result;43}44 45// Example usage:46// solveNQueens(4);47// Returns 2 distinct solutions:48// [49// [".Q..", "...Q", "Q...", "..Q."],50// ["..Q.", "Q...", "...Q", ".Q.."]51// ]Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Recursion stack & backtracking exploration animator
Test your understanding of N-Queens Problem complexity and step mechanics.
Q1.How many valid distinct solutions exist for the 8-Queens problem on an 8 × 8 board?
Q2.Why do `row - col` and `row + col` identify diagonals uniquely on a grid?
Apply N-Queens Problem to real coding interview questions.
Return all distinct board configurations for N-Queens.
Return the total number of distinct solutions to the N-Queens puzzle.