|
| 1 | +package net.olegg.aoc.year2024.day16 |
| 2 | + |
| 3 | +import net.olegg.aoc.someday.SomeDay |
| 4 | +import net.olegg.aoc.utils.Directions |
| 5 | +import net.olegg.aoc.utils.Directions.Companion.CCW |
| 6 | +import net.olegg.aoc.utils.Directions.Companion.CW |
| 7 | +import net.olegg.aoc.utils.Vector2D |
| 8 | +import net.olegg.aoc.utils.find |
| 9 | +import net.olegg.aoc.utils.get |
| 10 | +import net.olegg.aoc.year2024.DayOf2024 |
| 11 | +import java.util.PriorityQueue |
| 12 | + |
| 13 | +/** |
| 14 | + * See [Year 2024, Day 16](https://adventofcode.com/2024/day/16) |
| 15 | + */ |
| 16 | +object Day16 : DayOf2024(16) { |
| 17 | + private val empty = setOf('.', 'S', 'E') |
| 18 | + override fun first(): Any? { |
| 19 | + val start = matrix.find('S')!! |
| 20 | + val end = matrix.find('E')!! |
| 21 | + |
| 22 | + val queue = PriorityQueue<Triple<Vector2D, Directions, Int>>(compareBy { it.third }) |
| 23 | + queue.add(Triple(start, Directions.R, 0)) |
| 24 | + val seen = mutableSetOf<Pair<Vector2D, Directions>>() |
| 25 | + |
| 26 | + while (queue.isNotEmpty()) { |
| 27 | + val point = queue.remove() |
| 28 | + val (curr, dir, length) = point |
| 29 | + if (curr == end) { |
| 30 | + return length |
| 31 | + } |
| 32 | + val config = curr to dir |
| 33 | + if (config in seen) { |
| 34 | + continue |
| 35 | + } |
| 36 | + seen += config |
| 37 | + |
| 38 | + if (matrix[curr + dir.step] in empty) { |
| 39 | + queue.add(Triple(curr + dir.step, dir, length + 1)) |
| 40 | + } |
| 41 | + queue.add(Triple(curr, CW[dir]!!, length + 1000)) |
| 42 | + queue.add(Triple(curr, CCW[dir]!!, length + 1000)) |
| 43 | + } |
| 44 | + |
| 45 | + return -1 |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +fun main() = SomeDay.mainify(Day16) |
0 commit comments