-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtotalNQueens.ts
43 lines (33 loc) · 1011 Bytes
/
totalNQueens.ts
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
/**
* Time complexity O()
* Space complexity O()
*/
export const totalNQueens = (n: number): number => {
const solutions: string[][] = [];
const cols = new Set();
const posDiag = new Set();
const negDiag = new Set();
const board = Array.from({ length: n }, () => new Array(n).fill('.'));
function backtrack(row: number) {
if(row === n) {
solutions.push(board.map(a => a.join('')));
return;
}
for(let col = 0; col < n; col++) {
if(cols.has(col) || posDiag.has(row + col) || negDiag.has(row - col)) {
continue;
}
cols.add(col);
posDiag.add(row + col);
negDiag.add(row - col);
board[row][col] = 'Q';
backtrack(row + 1);
cols.delete(col);
posDiag.delete(row + col);
negDiag.delete(row - col);
board[row][col] = '.';
}
}
backtrack(0);
return solutions.length;
};