-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.js
64 lines (50 loc) · 1.62 KB
/
12.js
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
const isTesting = false;
const input = isTesting
? `Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi`
: ``;
const getIndexOfChar = (char) => {
const y = grid.findIndex((row) => row.includes(char));
const x = grid[y].indexOf(char);
return { x, y };
};
const grid = input.split("\n").map((row) => row.split(""));
const start = getIndexOfChar("S");
const end = getIndexOfChar("E");
const charA = "a".charCodeAt(0);
grid[start.y][start.x] = "a";
grid[end.y][end.x] = "z";
const numGrid = grid.map((row) => row.map((l) => l.charCodeAt(0) - charA));
const toStr = (coords) => JSON.stringify(coords);
const fromStr = (coords) => JSON.parse(coords);
const getNeighbours = ({ x, y }) => {
const neighbours = [];
if (x > 0) neighbours.push({ x: x - 1, y });
if (x < grid[0].length - 1) neighbours.push({ x: x + 1, y });
if (y > 0) neighbours.push({ x, y: y - 1 });
if (y < grid.length - 1) neighbours.push({ x, y: y + 1 });
return neighbours;
};
const stepGrid = Array.from(grid).map(() => Array.from(grid[0]).fill(Infinity));
const recurse = (coord, nSteps) => {
if (stepGrid[coord.y][coord.x] <= nSteps) return;
stepGrid[coord.y][coord.x] = nSteps;
getNeighbours(coord).forEach((neighbour) => {
if (numGrid[neighbour.y][neighbour.x] >= numGrid[coord.y][coord.x] - 1)
recurse(neighbour, nSteps + 1);
});
};
recurse(end, 0);
console.log("Part 1", stepGrid[start.y][start.x]);
let bestScore = stepGrid[start.y][start.x];
numGrid.forEach((row, y) => {
row.forEach((cell, x) => {
if (cell === 0 && stepGrid[y][x] < bestScore) {
bestScore = stepGrid[y][x];
}
});
});
console.log("Part 2", bestScore);