Skip to content

Commit e5cfee7

Browse files
committed
Create an initial dijkstra for 2023 Day 17
1 parent 7d45043 commit e5cfee7

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

adventofcode2023/Day17.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package adventofcode2023
2+
3+
import java.io.File
4+
import java.util.PriorityQueue
5+
6+
object Day17 {
7+
private val inputs = File("resources/adventofcode2023/Day17.txt")
8+
.readLines()
9+
.map { line ->
10+
line.toList().map { it.digitToInt() }
11+
}
12+
13+
private fun dijkstra(destinationX: Int, destinationY: Int): Int {
14+
data class Location(val x: Int, val y: Int, val distance: Int)
15+
16+
fun getNeighbors(x: Int, y: Int, distance: Int): Set<Location> {
17+
val neighbors = mutableSetOf<Location>()
18+
19+
if (x > 0) neighbors.add(Location(x - 1, y, distance + inputs[y][x - 1]))
20+
if (y > 0) neighbors.add(Location(x, y - 1, distance + inputs[y - 1][x]))
21+
if (x < inputs[0].size - 1) neighbors.add(Location(x + 1, y, distance + inputs[y][x + 1]))
22+
if (y < inputs.size - 1) neighbors.add(Location(x, y + 1, distance + inputs[y + 1][x]))
23+
24+
return neighbors
25+
}
26+
27+
val frontier = PriorityQueue<Location> { loc1, loc2 -> loc1.distance - loc2.distance }
28+
frontier.add(Location(0, 0, 0))
29+
val minDistances = Array(inputs[0].size) {Array<Int?>(inputs.size) { null } }
30+
minDistances[0][0] = 0
31+
32+
while (frontier.isNotEmpty()) {
33+
val current = frontier.remove()
34+
35+
if (current.x == destinationX && current.y == destinationY) return current.distance
36+
37+
getNeighbors(current.x, current.y, current.distance).forEach { neighbor ->
38+
if (minDistances[neighbor.x][neighbor.y] == null || minDistances[neighbor.x][neighbor.y]!! > neighbor.distance) {
39+
frontier.add(neighbor)
40+
minDistances[neighbor.x][neighbor.y] = neighbor.distance
41+
}
42+
}
43+
}
44+
45+
throw Exception("Location not found")
46+
}
47+
48+
fun part1() = println(dijkstra(inputs[0].size - 1, inputs.size - 1))
49+
}
50+
51+
fun main() {
52+
Day17.part1()
53+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy