Skip to content

Visualizers

N-Queens Visualizer

Step-through backtracking to place N non-attacking queens on a chessboard.

native Client-side
Ready to solve.

Execution Log

Solutions Found: 0
Backtracks: 0
Current Action:

Idle

Legend:

Queen Placed (Safe)
Queen Conflict
Light Square
Dark Square

N-Queens Backtracking 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 means that no two queens can share the same row, column, or diagonal.

How Backtracking Solves It

The algorithm searches for a solution recursively by placing queens row-by-row:

  1. Start in the top-left corner.
  2. Place a queen in the first available cell in the current row.
  3. Check if there are any conflicts (horizontal, vertical, diagonal) with previously placed queens.
  4. If there are no conflicts, recursively try to place a queen in the next row.
  5. If placing a queen leads to a dead end (no safe cells in a subsequent row), **backtrack**: remove the queen, and try the next column in the previous row.

Implementation

function solveNQueens(n) {
  const result = [];
  const board = Array(n).fill(-1); // board[r] = c
  
  function isSafe(row, col) {
    for (let i = 0; i < row; i++) {
      const otherCol = board[i];
      if (otherCol === col || 
          otherCol - i === col - row || 
          otherCol + i === col + row) {
        return false;
      }
    }
    return true;
  }
  
  function backtrack(row) {
    if (row === n) {
      result.push([...board]);
      return;
    }
    for (let col = 0; col < n; col++) {
      board[row] = col;
      if (isSafe(row, col)) {
        backtrack(row + 1);
      }
      board[row] = -1;
    }
  }
  
  backtrack(0);
  return result;
}