function calcAllPatterns(n) {
let totalPatterns = 0;
for (let len = 2; len <= n * n; len++) {
totalPatterns += calcPatterns1(n, len);
}
console.log(totalPatterns);
return totalPatterns;
}
function calcPatterns(n, minLen) {
let totalPatterns = calcPatterns1(n, minLen);
console.log(totalPatterns);
return totalPatterns;
}
function calcPatterns1(n, len, last = -1, visited = new Set()) {
if (visited.size == len) {
return 1;
}
let sum = 0;
if (last == -1) {
for (let i = 0; i < n * n; i++) {
visited.add(i); // Start from each cell
for (let j = 0; j < n * n; j++) {
if (!visited.has(j) && !hasPredecessor(i, j, n)) {
visited.add(j);
sum += calcPatterns1(n, len, i, visited);
visited.delete(j);
}
}
visited.delete(i);
}
return sum;
}
for (let i = 0; i < n * n; i++) {
if (!visited.has(i) && !hasPredecessor(last, i, n)) {
visited.add(i);
sum += calcPatterns1(n, len, i, visited);
visited.delete(i);
}
}
return sum;
}
function hasPredecessor(origin, target, n) {
let x1 = parseInt(origin / n);
let y1 = origin % n;
let x2 = parseInt(target / n);
let y2 = target % n;
if (x1 == x2) {
return Math.abs(y1 - y2) > 1; // Same row, not adjacent columns
}
if (y1 == y2) {
return Math.abs(x1 - x2) > 1; // Same column, not adjacent rows
}
return Math.abs(x1 - x2) > 1 || Math.abs(y1 - y2) > 1; // Diagonal adjacency check
}
calcPatterns(2, 2); // Example for 2x2 grid with min length 2 -> 12
calcPatterns(2, 3); // Example for 2x2 grid with min length 3 -> 24
calcPatterns(3, 2); // Example for 3x3 grid with min length 2
// 12 14 15 21 23 24 25 26 32 35
// 36 41 42 45 47 48 51 52 53 54
// 56 57 58 59 62 63 65 68 69 74
// 75 78 84 85 86 87 89 95 96 98 -> 40
calcPatterns(3, 3); // -> 160 ?
calcAllPatterns(2); // -> 60 ?
calcAllPatterns(3); // -> 10296 ?