This JavaScript program solves the classic N-Queens problem, which involves placing N queens on an NΓN chessboard such that no two queens attack each other. The program implements a backtracking algorithm to find all valid solutions and displays them in a readable format using emojis.
- Uses backtracking to explore all possible queen placements efficiently.
- Supports different board sizes by changing the value of
n. - Displays the solutions in a visual format using
πfor queens andβ¬for empty spaces. - Provides the total number of solutions found for a given
n.
- The
nQueens(n)function initializes an empty chessboard of sizen Γ n. - The
solveNQueens(board, row, n, solutions)function attempts to place queens row by row while ensuring they do not attack each other. - The
isSafe(board, row, col, n)function checks if a queen can be placed in a given position. - If a valid placement is found for all rows, a solution is added to the results.
- The program prints each solution using
printBoard(board).
- Install Node.js if you haven't already.
- Save the script as
nQueens.js. - Open a terminal and run the script using:
node nQueens.js
- Modify the
nvariable in the script to test different board sizes.
For n = 4, the script outputs:
Number of solutions for 4-Queens: 2
Solution 1:
1 β¬ π β¬ β¬
2 β¬ β¬ β¬ π
3 π β¬ β¬ β¬
4 β¬ β¬ π β¬
Solution 2:
1 β¬ β¬ π β¬
2 π β¬ β¬ β¬
3 β¬ β¬ β¬ π
4 β¬ π β¬ β¬
- The time complexity of the backtracking approach is O(N!) in the worst case.
- The space complexity is O(NΒ²) due to the board storage.
- The N-Queens problem has no solutions for ******
n = 2**** or ******n = 3. - The algorithm can be optimized using bitwise operations for larger values of
n.
This project is open-source and free to use.
Happy Coding! π