-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_038.js
52 lines (46 loc) Β· 1.1 KB
/
problem_038.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
/**
* @param {number} n
* @return {string[][]}
*/
function solveNQueens(n) {
const solutions = [];
explore(n, solutions, 0, []);
return solutions.map(solution =>
solution.map(col => '.'.repeat(col) + 'Q' + '.'.repeat(n - col - 1))
);
}
/**
* @param {number[]} colPlacements
* @param {number} col
* @return {boolean}
*/
function isValid(colPlacements, col) {
for (let row = 0; row < colPlacements.length; row++) {
const diffX = Math.abs(colPlacements[row] - col);
const diffY = colPlacements.length - row;
if (!diffX || diffX === diffY) { // same column or diagonal
return false;
}
}
return true;
}
/**
* @param {number} n
* @param {number[][]} solutions
* @param {number} row
* @param {number[]} colPlacements
* @return {void}
*/
function explore(n, solutions, row, colPlacements) {
if (row === n) {
return solutions.push(colPlacements.slice());
}
for (let col = 0; col < n; col++) {
if (!isValid(colPlacements, col)) {
continue;
}
colPlacements.push(col);
explore(n, solutions, row + 1, colPlacements);
colPlacements.pop();
}
}