30 lines
674 B
TypeScript
30 lines
674 B
TypeScript
export {};
|
|
|
|
const N: number = Number(require("fs").readFileSync(0).toString().trim());
|
|
|
|
let queen: number[] = new Array(N).fill(-1);
|
|
let count: number = 0;
|
|
|
|
const isSafe = (depth: number): boolean => {
|
|
for (let col=0; col<depth; col++) {
|
|
if (queen[col] === queen[depth]) return false;
|
|
else if (Math.abs(depth - col) === Math.abs(queen[depth] - queen[col])) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
const backTracking = (depth: number) => {
|
|
if (depth === N) {
|
|
count++;
|
|
return;
|
|
}
|
|
|
|
for (let n=0; n<N; n++) {
|
|
queen[depth] = n;
|
|
|
|
if (isSafe(depth)) backTracking(depth+1);
|
|
}
|
|
}
|
|
|
|
backTracking(0);
|
|
console.log(count); |