-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
86 lines (70 loc) · 1.63 KB
/
index.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
import {
INPUT_PATH,
runner,
directions,
SAMPLE_PATH,
splitLines,
getGrid,
} from '../../../lib/utils';
const path = `${__dirname}/${INPUT_PATH}`;
type Grid = number[][];
type Node = [number, number, number[][]];
const getStarts = (grid: Grid) => {
const starts: [number, number][] = [];
grid.forEach((row, y) => {
row.filter((cell, x) => {
if (cell === 0) starts.push([x, y]);
});
});
return starts;
};
const bfs = (grid: Grid, start: Node, end: number, visitOnce: boolean) => {
let score = 0;
const rows = grid.length;
const cols = grid[0].length;
const visited = getGrid(rows, cols, false);
const stack: Node[] = [start];
while (stack.length) {
const [x, y, path] = stack.shift()!;
if (grid[y][x] === end) {
score++;
}
for (const [dx, dy] of directions) {
const ny = y + dy;
const nx = x + dx;
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows) {
if (visitOnce && visited[ny][nx]) continue;
if (grid[ny][nx] - grid[y][x] === 1) {
visited[ny][nx] = true;
stack.push([nx, ny, [...path, [nx, ny]]]);
}
}
}
}
return score;
};
const solution = ({
input,
visitOnce,
}: {
input: string;
visitOnce: boolean;
}) => {
const grid = splitLines(input).map((row) => row.split('').map(Number));
return getStarts(grid).reduce(
(acc, [x, y]) => acc + bfs(grid, [x, y, []], 9, visitOnce),
0,
);
};
runner({
path,
solution: (input) => {
return solution({ input, visitOnce: true });
},
});
runner({
path,
solution: (input) => {
return solution({ input, visitOnce: false });
},
});