-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.ts
97 lines (77 loc) · 2.66 KB
/
part2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import * as fs from 'fs';
import { getNeighbors } from '../../utils';
const input = fs.readFileSync('input', 'utf8').split('\n');
const maxCheatCount = 20;
const shortcutRequired = 100;
let start = { x: 0, y: 0, isWall: false };
let end = { x: 0, y: 0, isWall: false };
let originalTime = undefined;
let originalTrack: { x: number; y: number }[] = [];
const maze = input.map((line, row) =>
line.split('').map((cell, column) => {
if (cell === 'S') {
return (start = { x: column, y: row, isWall: false });
} else if (cell === 'E') {
return (end = { x: column, y: row, isWall: false });
} else {
return { x: column, y: row, isWall: cell === '#' };
}
}),
);
const race = (
maze: { x: number; y: number; isWall: boolean }[][],
start: { x: number; y: number },
end: { x: number; y: number },
stopIfOver = undefined,
) => {
const queue = [{ x: start.x, y: start.y, steps: 0, visited: [start] }];
const visited = new Map();
visited.set(`${start.x},${start.y}`, 0);
let time = Infinity;
while (queue.length > 0) {
const current = queue.shift();
if (current.x === end.x && current.y === end.y) {
if (!originalTime && current.steps < time) {
originalTrack = current.visited;
}
time = Math.min(current.steps, time);
continue;
}
const neighbors = getNeighbors(maze, current).filter((cell) => cell && !cell.isWall);
let searches = neighbors
.map((neighbor) => ({
x: neighbor.x,
y: neighbor.y,
steps: current.steps + 1,
visited: !originalTime ? [...current.visited, neighbor] : [],
}))
.filter((search) => {
const key = `${search.x},${search.y}`;
if (stopIfOver && visited > stopIfOver) return false;
return !visited.has(key) || visited.get(key) > search.steps;
});
queue.push(...searches);
searches.forEach((search) => visited.set(`${search.x},${search.y}`, search.steps));
}
return time;
};
originalTime = race(maze, start, end);
let result = 0;
originalTrack.forEach((cheatStart, startIndex) => {
const visited = originalTrack.slice(0, startIndex);
const mazeClone = maze.map((row) => row.map((grid) => ({ ...grid })));
visited.forEach((pos) => (mazeClone[pos.y][pos.x].isWall = true));
originalTrack.forEach((cheatEnd, endIndex) => {
if (endIndex <= startIndex) return;
const cheatCount = Math.abs(cheatStart.x - cheatEnd.x) + Math.abs(cheatStart.y - cheatEnd.y);
if (cheatCount <= 1 || cheatCount > maxCheatCount) return;
if (originalTrack[startIndex + cheatCount] === cheatEnd)
// Ignore cheat that's already on track
return;
const time = startIndex + cheatCount + (originalTime - endIndex);
if (originalTime - time >= shortcutRequired) {
result++;
}
});
});
console.log(result);