Skip to content

Commit dd17f2b

Browse files
committed
Implement day 16 part 2
1 parent ad5e524 commit dd17f2b

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

day16/src/day16.kts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,46 +17,55 @@ data class Vec2(val x: Int, val y: Int) {
1717
operator fun plus(rhs: Vec2) = Vec2(x + rhs.x, y + rhs.y)
1818
}
1919

20-
data class Node(val total: Int, val pos: Vec2, val dir: Vec2)
20+
data class Node(val total: Int, val visited: Set<Vec2>, val pos: Vec2, val dir: Vec2)
21+
22+
data class ShortestPaths(val length: Int, val visited: Set<Vec2>)
2123

2224
data class Board(val rows: List<String>) {
2325
val height: Int get() = rows.size
2426
val width: Int get() = rows[0].length
2527

2628
operator fun get(pos: Vec2): Char = rows[pos.y][pos.x]
2729

28-
fun shortestPath(start: Vec2, end: Vec2): Int {
30+
fun shortestPaths(start: Vec2, end: Vec2): ShortestPaths {
2931
// Your run-of-the-mill Dijkstra implementation below
3032

3133
val queue = PriorityQueue<Node>(11) { l, r -> l.total - r.total }
3234
val visited = mutableSetOf<Pair<Vec2, Vec2>>()
3335

3436
val startDir: Vec2 = Vec2(1, 0)
35-
queue.add(Node(0, start, startDir))
37+
queue.add(Node(0, setOf(start), start, startDir))
3638
visited.add(Pair(start, startDir))
3739

40+
var shortestTotal: Int? = null
41+
val shortestPaths = mutableSetOf<Vec2>()
42+
3843
while (!queue.isEmpty()) {
3944
val node = queue.poll()
45+
if (shortestTotal?.let { node.total > it } ?: false) {
46+
break
47+
}
4048
if (node.pos == end) {
41-
return node.total
49+
shortestTotal = node.total
50+
shortestPaths.addAll(node.visited)
4251
}
4352
visited.add(Pair(node.pos, node.dir))
4453

4554
// Step
4655
val next = node.pos + node.dir
4756
if (Pair(next, node.dir) !in visited && this[next] != '#') {
48-
queue.add(Node(node.total + 1, next, node.dir))
57+
queue.add(Node(node.total + 1, node.visited.union(listOf(next)), next, node.dir))
4958
}
5059

5160
// Rotate
5261
for (dir in listOf(node.dir.rotateCW(), node.dir.rotateCCW())) {
5362
if (Pair(node.pos, dir) !in visited) {
54-
queue.add(Node(node.total + 1000, node.pos, dir))
63+
queue.add(Node(node.total + 1000, node.visited, node.pos, dir))
5564
}
5665
}
5766
}
5867

59-
throw RuntimeException("No path found")
68+
return shortestTotal?.let { ShortestPaths(it, shortestPaths) } ?: throw RuntimeException("No path found")
6069
}
6170
}
6271

@@ -66,4 +75,6 @@ val board = Board(File(args[0]).readLines())
6675
val start = Vec2(1, board.height - 2)
6776
val end = Vec2(board.width - 2, 1)
6877

69-
println("Part 1: ${board.shortestPath(start, end)}")
78+
val result = board.shortestPaths(start, end)
79+
println("Part 1: ${result.length}")
80+
println("Part 2: ${result.visited.size}")

0 commit comments

Comments
 (0)