Login

N-Queens Problem

Write a function that returns the number of possible solutions to the N-Queens problem.

Advanced


Instructions

Write a function that takes an integer N as input and returns the number of possible solutions to the N-Queens problem. The function should return the number of possible solutions. In chess, a queen can move horizontally, vertically, or diagonally, so no two queens can share the same row, column, or diagonal. The function should return the number of possible solutions. In the N-Queens problem you have to place N queens on an N×N chessboard in such a way that no two queens threaten each other.

Tests
0/4
Function Call:
Expected:
solveNQueens(2)
0
Run test

solveNQueens(4)
2
Run test

solveNQueens(11)
2680
Run test

Hidden Test
?
Run test

See Solution

Solution

Basic idea

Here's a general approach to solving the N-Queens problem using backtracking:

  • Start with an empty N×N chessboard.
  • Place a queen in the first row.
  • Move to the next row and place a queen in a safe position.
  • Continue this process recursively until all queens are placed or until it's not possible to place a queen without violating the constraints.
  • If a solution is found (i.e., all queens are placed), add it to the list of solutions.
  • Backtrack to explore other possibilities.
const solveNQueens = (n) => {
    const result = [];
    
    // Helper function to check if a queen can be placed at position (row, col)
    function isSafe(board, row, col) {
        // Check if there's a queen in the same column
        for (let i = 0; i < row; i++) {
            if (board[i] === col || 
                board[i] === col - (row - i) || 
                board[i] === col + (row - i)) {
                return false;
            }
        }
        return true;
    }
    
    // Helper function to recursively find all solutions
    const backtrack = (row, board) => {
        if (row === n) {
            // If all queens are placed, add the current board configuration to the result
            result.push(board.map(col => '.'.repeat(col) + 'Q' + '.'.repeat(n - col - 1)));
            return;
        }
        
        // Try placing the queen in each column of the current row
        for (let col = 0; col < n; col++) {
            if (isSafe(board, row, col)) {
                board.push(col);
                backtrack(row + 1, board);
                board.pop(); // Backtrack
            }
        }
    }
    
    backtrack(0, []);
    return result.length;
}

Explanation

  1. The solveNQueens function takes an integer n as input and returns the number of possible solutions to the N-Queens problem.
  2. The function initializes an empty array result to store the solutions.
  3. The isSafe function checks if a queen can be placed at position (row, col) on the board.
  4. The backtrack function is a recursive helper function that finds all solutions to the N-Queens problem.
  5. The base case of the recursion is when row === n, i.e., all queens are placed on the board.
  6. If the base case is reached, the current board configuration is added to the result array.
  7. The backtrack function tries placing the queen in each column of the current row, checking if it is safe to place the queen at that position.
  8. If it is safe, the queen is placed in that column, and the function is called recursively for the next row.
  9. After the recursive call, the queen is removed from the board to backtrack and try other positions.
  10. The solveNQueens function calls the backtrack function with the initial row set to 0 and an empty board configuration.
  11. Finally, the function returns the length of the result array, which contains all possible solutions to the N-Queens problem.

Complexity Analysis

The time complexity of this solution is O(N!), where N is the size of the chessboard. This is because the function tries all possible combinations of queen placements on the board.

More about backtracking

Definition

Backtracking is a technique used to find solutions incrementally by trying different options and abandoning those that fail to satisfy the constraints of the problem.

Application

Backtracking is useful for solving problems with a constraint satisfaction aspect, such as finding a path through a maze, solving Sudoku puzzles, or solving the N-Queens problem.

Any improvement idea? Share with us!