101 Logo
onenoughtone

N-Queens Pattern

What is the N-Queens Problem?

The N-Queens problem is a classic chess puzzle: place N queens on an N×N chessboard so that no two queens threaten each other.

This means no two queens can share the same row, column, or diagonal.

Backtracking Approach

The N-Queens problem is a perfect example of backtracking:

  1. Start with an empty board
  2. Try placing a queen in the first row, first column
  3. Move to the next row and try placing a queen in a valid position
  4. If no valid position exists, backtrack to the previous row and try a different position
  5. Continue until all queens are placed or all possibilities are exhausted

Implementation

Here's how we can implement the N-Queens solution using backtracking:

function solveNQueens(n) { const result = []; const board = Array(n).fill().map(() => Array(n).fill('.')); function backtrack(row) { // Base case: If we've placed queens in all rows, we have a valid solution if (row === n) { // Convert the board to the required format and add to result const solution = board.map(row => row.join('')); result.push(solution); return; } // Try placing a queen in each column of the current row for (let col = 0; col < n; col++) { if (isValid(row, col)) { // Place the queen board[row][col] = 'Q'; // Recursively place queens in the next row backtrack(row + 1); // Backtrack: remove the queen to try other positions board[row][col] = '.'; } } } function isValid(row, col) { // Check if there's a queen in the same column for (let i = 0; i < row; i++) { if (board[i][col] === 'Q') { return false; } } // Check upper-left diagonal for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] === 'Q') { return false; } } // Check upper-right diagonal for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (board[i][j] === 'Q') { return false; } } return true; } backtrack(0); return result; }

Time and Space Complexity

Time Complexity:

O(N!), where N is the size of the board. In the worst case, we need to explore all possible placements of queens.

Space Complexity:

O(N²) for the board representation, plus O(N) for the recursion stack.

IntroVisualizePatternsPractice
101 Logo
onenoughtone