This commit is contained in:
2024-12-16 22:23:04 +00:00
parent ce848f3f16
commit 4dd516d9dc

View File

@@ -91,7 +91,6 @@ function fillDeadEnd(pos: Coord): void {
};
}
printMap();
for (let y = 1; y < height - 1; y++) {
for (let x = 1; x < width - 1; x++) {
const pos = { x, y };
@@ -104,29 +103,30 @@ for (let y = 1; y < height - 1; y++) {
}
}
}
printMap();
let fastest: number|null = null;
const scoreCache: { [key: string]: [number, Coord, Dir] } = {};
const scores: Array<number> = [];
const branchCache: { [key: string]: number } = {};
const scores: Array<[number, Array<string>]> = [];
function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Array<string> = [], lastBranch: [number, Coord]|null = null): void {
if (fastest !== null && currentScore >= fastest) {
return;
}
const cache = scoreCache[`${pos.x},${pos.y}`];
if (cache) {
currentScore += cache[0];
pos = cache[1];
dir = cache[2];
}
const branch = isBranch(pos, dir);
if (branch) {
const cacheKey = `${pos.x},${pos.y},${dir}`;
const cache = branchCache[cacheKey];
if (cache && cache < currentScore) {
return;
} else {
branchCache[cacheKey] = currentScore;
}
if (lastBranch) {
scoreCache[`${lastBranch[1].x},${lastBranch[1].y}`] = [currentScore - lastBranch[0], pos, dir];
console.log(scoreCache);
}
lastBranch = [currentScore, pos];
}
@@ -142,7 +142,7 @@ function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Ar
fastest = score;
}
lastBranch = null;
scores.push(score);
scores.push([score, [...path, nextStr]]);
return;
} else if (nextChar === '.') {
getScoresAfterPosition(next, newDir, score, [...path, nextStr], branch ? [score, next] : lastBranch);
@@ -155,4 +155,13 @@ function getScoresAfterPosition(pos: Coord, dir: Dir, currentScore = 0, path: Ar
getScoresAfterPosition(snakePos, snakeDir);
console.log(Math.min(...scores));
const fastestScore = Math.min(...scores.map(([score]) => score));
let coordsOnPaths: Set<string> = new Set();
scores.forEach(([score, path]) => {
if (score === fastestScore) {
path.forEach((coord) => coordsOnPaths.add(coord));
}
});
console.log(coordsOnPaths.size + 1);