-
Notifications
You must be signed in to change notification settings - Fork 45
/
024problem.js
39 lines (32 loc) · 1.1 KB
/
024problem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function solveNQueens(n) {
const solutions = [];
const board = Array.from({ length: n }, () => Array(n).fill('.'));
const isSafe = (board, row, col) => {
for (let i = 0; i < row; i++) {
if (board[i][col] === 'Q') return false;
// Check upper left diagonal
if (col - (row - i) >= 0 && board[i][col - (row - i)] === 'Q') return false;
// Check upper right diagonal
if (col + (row - i) < n && board[i][col + (row - i)] === 'Q') return false;
}
return true;
}
const solve = (currentRow) => {
if (currentRow === n) {
solutions.push(board.map(row => row.join('')));
return;
}
for (let i = 0; i < n; i++) {
if (isSafe(board, currentRow, i)) {
board[currentRow][i] = 'Q';
solve(currentRow + 1);
board[currentRow][i] = '.';
}
}
}
solve(0);
return solutions;
}
// For example, to solve for a 4x4 board:
const solutions = solveNQueens(4);
console.log(solutions);