Skip to content

Commit 9b07770

Browse files
Create N_queen.js
closes #365'
1 parent 5b38b55 commit 9b07770

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Famous Algorithms/N_queen.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
function solveNQueens(n) {
2+
const board = new Array(n).fill().map(() => new Array(n).fill('.')); // Create an empty NxN chessboard
3+
4+
const solutions = [];
5+
6+
function isSafe(row, col) {
7+
// Check if no other queens are in the same column
8+
for (let i = 0; i < row; i++) {
9+
if (board[i][col] === 'Q') {
10+
return false;
11+
}
12+
}
13+
14+
// Check upper-left diagonal
15+
for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) {
16+
if (board[i][j] === 'Q') {
17+
return false;
18+
}
19+
}
20+
21+
// Check upper-right diagonal
22+
for (let i = row, j = col; i >= 0 && j < n; i--, j++) {
23+
if (board[i][j] === 'Q') {
24+
return false;
25+
}
26+
}
27+
28+
return true;
29+
}
30+
31+
function solve(row) {
32+
if (row === n) {
33+
// Found a valid solution, push a copy of the board to the solutions array
34+
solutions.push(board.map(row => row.join('')));
35+
return;
36+
}
37+
38+
for (let col = 0; col < n; col++) {
39+
if (isSafe(row, col)) {
40+
board[row][col] = 'Q'; // Place a queen
41+
solve(row + 1); // Recursively move to the next row
42+
board[row][col] = '.'; // Backtrack by removing the queen
43+
}
44+
}
45+
}
46+
47+
solve(0); // Start solving from the first row
48+
49+
return solutions;
50+
}
51+
52+
// Example usage:
53+
const n = 4; // Change this to the desired board size
54+
const solutions = solveNQueens(n);
55+
56+
console.log(`Solutions for ${n}-Queens:`);
57+
for (const solution of solutions) {
58+
console.log(solution);
59+
}

0 commit comments

Comments
 (0)