Code to Solve the N-Queens Puzzle
Practical implementations in JavaScript, Python and other languages to solve the N-Queens puzzle.
Code Example
Select a programming language to see the backtracking algorithm implementation:
function solveNQueens(n = 8) {
const solutions = [];
const board = Array(n).fill(-1);
function isSafe(row, col) {
for (let i = 0; i < row; i++) {
const queenCol = board[i];
if (queenCol === col ||
Math.abs(queenCol - col) === Math.abs(i - row)) {
return false;
}
}
return true;
}
function backtrack(row) {
if (row === n) {
solutions.push([...board]);
return;
}
for (let col = 0; col < n; col++) {
if (isSafe(row, col)) {
board[row] = col;
backtrack(row + 1);
board[row] = -1;
}
}
}
backtrack(0);
return solutions;
}
const solutions = solveNQueens(8);
console.log(`Found ${solutions.length} solutions`);
Explanation
- The isSafe function checks if it's safe to place a queen at a given position.
- The backtrack function recursively tries all possible positions.
- When all 8 queens are placed, the solution is saved to the solutions array.
- The time complexity is O(N!), where N is the board size.
Complete Code to Solve the N-Queens Puzzle
The N-Queens puzzle can be efficiently implemented in any modern programming language that supports recursion. The implementations shown here demonstrate how the same backtracking algorithm can be expressed idiomatically in JavaScript, Python, Java, C++, C#, and PHP. Each implementation follows the same fundamental algorithmic principles but leverages the specific features and best practices of each language.
Performance Analysis by Language
The performance of the backtracking algorithm for N-Queens varies significantly depending on the programming language used. C++ and Java generally offer the best performance due to their compilation to native code and compiler optimizations. Python, while slower in execution, offers very readable syntax that facilitates algorithm understanding. JavaScript is ideal for interactive web implementations, while PHP is perfect for server-side web applications.
Language-Specific Optimizations
- JavaScript: Use typed arrays for better performance, implement Web Workers for intensive calculations
- Python: Use NumPy for vectorized operations, implement memoization with functools.lru_cache
- Java: Use ArrayList instead of regular arrays, implement parallelization with CompletableFuture
- C++: Use std::vector, implement compiler optimizations with -O3
Programming Best Practices for N-Queens
When implementing the backtracking algorithm for N-Queens, it's crucial to follow programming best practices. This includes using descriptive variable names like "board", "row", "col" instead of generic names. The code should be well-commented to explain the algorithm logic, especially the safety checking function and the backtracking process. Functions should be small and focused on a single responsibility.
Testing and Debugging N-Queens Code
Testing N-Queens code should include test cases for different board sizes, from 4x4 to 12x12. It's important to verify that the number of solutions found matches known values: 8 queens has 92 solutions, 9 queens has 352 solutions, etc. Debugging can be facilitated by implementing detailed logging of the backtracking process and visualization of found solutions.
Practical Applications of the Code
The code for solving N-Queens has practical applications beyond the original puzzle. It's used in scheduling algorithms, resource optimization, and assignment problems. In web development, it can be implemented as an interactive game, educational tool, or component of a machine learning system. The algorithm's versatility makes it an excellent foundation for more complex projects.