Skip to content

Commit c7ab2d1

Browse files
Created file nqueens.js at folder Backtracking ans deleted nqueens from the AlgorithmsToDo -file
1 parent 3d73e37 commit c7ab2d1

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

‎Backtracking/nqueens.js‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
var solveNQueens = function(n) {
2+
const result = [];
3+
solveNQueen(result, n);
4+
return result;
5+
};
6+
7+
function solveNQueen(result, size, board = [], row = 0) {
8+
if (row === size) {
9+
buildResult(result, board, size);
10+
return;
11+
}
12+
13+
for(let col = 0; col < size; col++) {
14+
if (safeToPlaceQuen(board, row, col, size)) {
15+
board.push(col);
16+
solveNQueen(result, size, board, row + 1);
17+
board.pop();
18+
}
19+
}
20+
}
21+
22+
function safeToPlaceQuen(board, row1, col1, size) {
23+
for( let row2 = 0; row2 < row1; row2++) {
24+
const col2 = board[row2];
25+
26+
if (col1 === col2) {
27+
return false;
28+
}
29+
30+
const colDist = Math.abs(col1 - col2);
31+
const rowDist = row1 - row2;
32+
33+
if (colDist === rowDist) {
34+
return false;
35+
}
36+
}
37+
38+
return true;
39+
}
40+
41+
function buildResult(result, board, size) {
42+
const boardWithQueens = board.map(col =>
43+
'.'.repeat(col) + 'Q' + '.'.repeat(size - col - 1)
44+
)
45+
46+
result.push(boardWithQueens);
47+
}
48+
49+
50+
51+
//sample
52+
console.log(solveNQueens(4));

0 commit comments

Comments
 (0)