Day 18 part 1

This commit is contained in:
Sven Weidauer 2024-12-25 12:21:38 +01:00
parent 598e8bd639
commit e0547c2309
4 changed files with 3507 additions and 31 deletions

View file

@ -0,0 +1,32 @@
import java.util.*
fun <T> dijkstra(start: T, goal: (T) -> Boolean, neighbors: (T) -> Sequence<Pair<T, Int>>): Int? {
val distanceFromStart = mutableMapOf(start to 0)
val visited = mutableSetOf<T>()
val queue = PriorityQueue<Pair<T, Int>> { a, b -> a.second.compareTo(b.second) }
queue.add(start to 0)
while (true) {
val (current, totalDistance) = queue.poll() ?: break
if (goal(current)) {
return totalDistance
}
visited.add(start)
for ((neighbor, distance) in neighbors(current)) {
if (neighbor in visited) continue;
val newDistance = totalDistance + distance
val currentDistance = distanceFromStart[neighbor]
if (currentDistance == null || newDistance < currentDistance) {
distanceFromStart[neighbor] = newDistance
queue.add(neighbor to newDistance)
}
}
}
return null
}

View file

@ -31,34 +31,3 @@ fun Direction.turns(to: Direction): Int = when {
this == Direction.West && to == Direction.East -> 2 this == Direction.West && to == Direction.East -> 2
else -> error("Missing directions") else -> error("Missing directions")
} }
fun <T> dijkstra(start: T, goal: (T) -> Boolean, neighbors: (T) -> Sequence<Pair<T, Int>>): Int? {
val distanceFromStart = mutableMapOf(start to 0)
val visited = mutableSetOf<T>()
val queue = PriorityQueue<Pair<T, Int>> { a, b -> a.second.compareTo(b.second) }
queue.add(start to 0)
while (true) {
val (current, totalDistance) = queue.poll() ?: break
if (goal(current)) {
return totalDistance
}
visited.add(start)
for ((neighbor, distance) in neighbors(current)) {
if (neighbor in visited) continue;
val newDistance = totalDistance + distance
val currentDistance = distanceFromStart[neighbor]
if (currentDistance == null || newDistance < currentDistance) {
distanceFromStart[neighbor] = newDistance
queue.add(neighbor to newDistance)
}
}
}
return null
}

View file

@ -0,0 +1,25 @@
fun main() {
val size = 71
val memory = readInput("day18.txt")
.map {
val (a, b) = it.split(',', limit = 2)
Grid.Coordinate(a.toInt(), b.toInt())
}
.take(1024)
.fold(CharGrid(size, size, '.')) { acc, coordinate ->
acc[coordinate] = '#'
acc
}
val start = Grid.Coordinate(0, 0)
val goal = Grid.Coordinate(size - 1, size - 1)
val distance = dijkstra(start, goal = { it == goal }, neighbors = { pos ->
Direction.entries.asSequence()
.map { pos.step(it) }
.filter { it in memory && memory[it] == '.' }
.map { it to 1 }
})
println("Part 1: $distance")
}

File diff suppressed because it is too large Load diff