-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnQueens.js
58 lines (48 loc) · 1.19 KB
/
nQueens.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
let result = [];
const queens = Array(n).fill(-1);
function makeBoard() {
const board = [];
for (let r = 0; r< n; ++r) {
let row = "";
for (let c = 0; c< n; ++c) {
if(queens[r] === c) {
// q
row = row + 'Q';
} else {
// .
row = row + '.';
}
}
board.push(row);
}
return board;
}
function isValid(row, col) {
for(let i = 0; i< row; ++i) {
if(queens[i] == col || Math.abs(i - row) == Math.abs(queens[i]- col))
return false;
}
return true;
}
function solve(row) {
if(row === n) {
const board = makeBoard();
result.push(board);
}
for(let col = 0; col < n ; ++col) {
if(!isValid(row, col)) {
continue;
}
queens[row] = col;
solve(row + 1);
queens[row] = -1;
}
}
solve(0);
return result;
};