-
Notifications
You must be signed in to change notification settings - Fork 154
/
n-queens-ii.js
48 lines (40 loc) · 933 Bytes
/
n-queens-ii.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
/**
* N-Queens II
*
* Follow up for N-Queens problem.
*
* Now, instead outputting board configurations, return the total number of distinct solutions.
*/
/**
* @param {number} n
* @return {number}
*/
const totalNQueens = n => {
const isValid = (row, columns) => {
for (let i = 0; i < row; i++) {
if (columns[i] === columns[row]) {
return false; // Two queues are in the same column
}
if (row - i === Math.abs(columns[row] - columns[i])) {
return false; // Two queues are in the same diagonal
}
}
return true;
};
const backtracking = (n, row, columns) => {
if (row === n) {
count++;
return;
}
for (let j = 0; j < n; j++) {
columns[row] = j;
if (isValid(row, columns)) {
backtracking(n, row + 1, columns);
}
}
};
let count = 0;
backtracking(n, 0, []);
return count;
};
export default totalNQueens;