-
Notifications
You must be signed in to change notification settings - Fork 0
/
day12-part2.js
113 lines (85 loc) · 2.56 KB
/
day12-part2.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const fs = require('fs');
const file = './input.txt';
const input = fs.readFileSync(file, { encoding: 'utf-8'});
const grid = input.split('\n').map(e => e.split(''));
const start = {
x: -1,
y: -1,
effort: 0
}
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 'S') {
start.x = j;
start.y = i;
break;
}
}
if (start.x !== -1) {
break;
}
}
grid[start.y][start.x] = 'a';
let possibleAStarts = [];
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 'a') {
possibleAStarts.push({
x: j,
y: i,
effort: 0
});
break;
}
}
}
let possibleMoves = [];
possibleMoves.push(start);
let visitedSquares = [];
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let effortNeeded = 0;
let possibleAnswers = [];
while (possibleAStarts.length > 0) {
possibleMoves = [];
possibleMoves.push(possibleAStarts.pop());
visitedSquares = [];
effortNeeded = 0;
possibleAnswers.push(compute());
}
console.log('ANSWER: ' + possibleAnswers.sort((a, b) => a-b)[0]);
function compute() {
while (possibleMoves.length > 0) {
const moveToTry = possibleMoves.shift();
visitedSquares.push(moveToTry);
const squaresToVisit = [
{ x: moveToTry.x - 1, y: moveToTry.y },
{ x: moveToTry.x + 1, y: moveToTry.y },
{ x: moveToTry.x, y: moveToTry.y - 1 },
{ x: moveToTry.x, y: moveToTry.y + 1 }
].filter(a => a.x > -1 && a.x < grid[moveToTry.y].length && a.y > -1 && a.y < grid.length);
for (let squareToVisit of squaresToVisit) {
if (visitedSquares.find(a => a.x === squareToVisit.x && a.y === squareToVisit.y) !== undefined) {
continue;
}
if (possibleMoves.find(a => a.x === squareToVisit.x && a.y === squareToVisit.y) !== undefined) {
continue;
}
if (grid[squareToVisit.y][squareToVisit.x] === 'E' && 'yz'.indexOf(grid[moveToTry.y][moveToTry.x]) === -1) {
continue;
}
if (alphabet.indexOf(grid[squareToVisit.y][squareToVisit.x]) > alphabet.indexOf(grid[moveToTry.y][moveToTry.x]) + 1) {
continue;
}
if (grid[squareToVisit.y][squareToVisit.x] === 'E') {
effortNeeded = moveToTry.effort + 1;
console.log(effortNeeded);
return effortNeeded;
}
possibleMoves.push({
x: squareToVisit.x,
y: squareToVisit.y,
effort: moveToTry.effort + 1
});
}
}
}