Skip to content

Commit ad5e524

Browse files
committed
Implement day 16 part 1
1 parent 5266a03 commit ad5e524

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

day16/resources/demo2.txt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#################
2+
#...#...#...#..E#
3+
#.#.#.#.#.#.#.#.#
4+
#.#.#.#...#...#.#
5+
#.#.#.#.###.#.#.#
6+
#...#.#.#.....#.#
7+
#.#.#.#.#.#####.#
8+
#.#...#.#.#.....#
9+
#.#.#####.#.###.#
10+
#.#.#.......#...#
11+
#.#.###.#####.###
12+
#.#.#...#.....#.#
13+
#.#.#.#####.###.#
14+
#.#.#.........#.#
15+
#.#.#.#########.#
16+
#S#.............#
17+
#################

day16/src/day16.kts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,25 +26,32 @@ data class Board(val rows: List<String>) {
2626
operator fun get(pos: Vec2): Char = rows[pos.y][pos.x]
2727

2828
fun shortestPath(start: Vec2, end: Vec2): Int {
29-
val queue = PriorityQueue<Node>(11) { l, r -> r.total - l.total }
29+
// Your run-of-the-mill Dijkstra implementation below
30+
31+
val queue = PriorityQueue<Node>(11) { l, r -> l.total - r.total }
3032
val visited = mutableSetOf<Pair<Vec2, Vec2>>()
3133

32-
val startDir: Vec2 = Vec2(0, -1)
34+
val startDir: Vec2 = Vec2(1, 0)
3335
queue.add(Node(0, start, startDir))
3436
visited.add(Pair(start, startDir))
3537

3638
while (!queue.isEmpty()) {
3739
val node = queue.poll()
38-
println("${node.pos} and ${this[node.pos]}")
3940
if (node.pos == end) {
4041
return node.total
4142
}
4243
visited.add(Pair(node.pos, node.dir))
43-
for (dir in listOf(node.dir, node.dir.rotateCW(), node.dir.rotateCCW())) {
44-
val next = node.pos + dir
45-
val weight = if (dir == node.dir) 1 else 1001
46-
if (Pair(next, dir) !in visited && this[next] != '#') {
47-
queue.add(Node(node.total + weight, next, dir))
44+
45+
// Step
46+
val next = node.pos + node.dir
47+
if (Pair(next, node.dir) !in visited && this[next] != '#') {
48+
queue.add(Node(node.total + 1, next, node.dir))
49+
}
50+
51+
// Rotate
52+
for (dir in listOf(node.dir.rotateCW(), node.dir.rotateCCW())) {
53+
if (Pair(node.pos, dir) !in visited) {
54+
queue.add(Node(node.total + 1000, node.pos, dir))
4855
}
4956
}
5057
}
@@ -59,4 +66,4 @@ val board = Board(File(args[0]).readLines())
5966
val start = Vec2(1, board.height - 2)
6067
val end = Vec2(board.width - 2, 1)
6168

62-
print("Part 1: ${board.shortestPath(start, end)}")
69+
println("Part 1: ${board.shortestPath(start, end)}")

0 commit comments

Comments
 (0)