-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
54 lines (42 loc) · 1.03 KB
/
solution.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
44
45
46
47
48
49
50
51
52
53
54
/*
* @lc app=leetcode id=52 lang=javascript
*
* [52] N-Queens II
*/
// @lc code=start
type RowQIndexList = (number | undefined)[];
/**
* @param {number} n
* @return {number}
*/
const totalNQueens = (n: number): number => {
// * ['60 ms', '80.28 %', '34.3 MB', '100 %']
const queens: RowQIndexList = new Array(n);
let results = 0;
const loopRun = (queens: RowQIndexList, row = 0): void => {
// * filled as solved, push valid solution
if (queens[n - 1] !== undefined) {
results += 1;
return;
}
for (let i = 0; i < n; i++) {
queens[row] = i;
if (checkQueens(queens, row)) {
loopRun(queens, row + 1);
}
queens[row] = undefined;
}
};
loopRun(queens);
return results;
};
const checkQueens = (queens: RowQIndexList, row: number): boolean => {
const e = queens[row];
for (let i = 0; i < row; i++) {
const k = queens[i]!;
if (k === e || k - row + i === e || k + row - i === e) return false;
}
return true;
};
// @lc code=end
export { totalNQueens };