-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueen8.ts
More file actions
30 lines (27 loc) · 789 Bytes
/
Copy pathqueen8.ts
File metadata and controls
30 lines (27 loc) · 789 Bytes
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
let res = {};
let total = 0, tried = 0;
function queen(depth: number, n: number) {
if (depth > n) {
console.log(res)
total++
return;
}
for (let i = 1; i <= n; i++) {
// 清除上次递归数据
for (let i = depth; i <= n; i++) {
delete res[i]
}
const isSameCol = Object.values(res).includes(i)
const isSameRightDiagonal = Object.keys(res).map((l) => Number(res[l]) - Number(l)).includes(i - depth);
const isSameLeftDiagonal = Object.keys(res).map((l) => Number(res[l]) + Number(l)).includes(depth + i);
tried++
if (!isSameCol && !isSameRightDiagonal && !isSameLeftDiagonal) {
res[depth] = i;
queen(depth + 1, n)
}
}
}
let start = Date.now()
queen(1, 8)
let end = Date.now()
console.log(total, tried, end - start)