-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBacktracking_N-Queens.js
More file actions
42 lines (34 loc) · 1.12 KB
/
Copy pathBacktracking_N-Queens.js
File metadata and controls
42 lines (34 loc) · 1.12 KB
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
/**
* @param {number} n
* @return {number}
*/
var totalNQueens = function(n) {
let out = 0;
function backtrack(row=0, cols=new Set(), diagonals = new Set(), antiDiagonals = new Set()) {
// check if found solution
if(row === n) {
out ++;
return;
}
// iterate all possible candiates
for(let col=0; col<n; col++) {
const [currDiagonal, currAntiDiagonal] = [row-col, row+col];
// is not Valid
if(cols.has(col) || diagonals.has(currDiagonal) || antiDiagonals.has(currAntiDiagonal)) {
continue;
}
// place
cols.add(col);
diagonals.add(currDiagonal);
antiDiagonals.add(currAntiDiagonal);
// backtrack / explorer further
backtrack(row+1,cols, diagonals, antiDiagonals);
// remove
cols.delete(col);
diagonals.delete(currDiagonal);
antiDiagonals.delete(currAntiDiagonal);
}
}
backtrack(0);
return out;
}