@@ -23,49 +23,27 @@ class Day20(val input: List<String>) : Day<Int, Int, Pair<Array<CharArray>, Pair
23
23
}
24
24
25
25
private fun solve (maxDistance : Int , lim : Int ): Int {
26
- val shortestPath = bfs(start, end)
27
- val size = shortestPath.size
28
- val fromStart = shortestPath.mapIndexed { idx, pos -> pos to idx }.toMap()
29
- val toEnd = shortestPath.mapIndexed { idx, pos -> pos to size - idx }.toMap()
30
- return shortestPath
31
- .asSequence()
32
- .flatMapIndexed { idx, from ->
33
- shortestPath
34
- .subList(idx + 1 , size)
35
- .mapNotNull { to -> from.manhattanDistance(to).let { if (it in 2 .. maxDistance) it to to else null } }
36
- .map { to -> size - (fromStart[from]!! + to.first + toEnd[to.second]!! ) }
37
- .filter { it > 0 }
26
+ val shortestPath = getPath().toTypedArray()
27
+ return shortestPath.indices
28
+ .sumOf { from ->
29
+ ((from + lim).. < shortestPath.size).count { end ->
30
+ val manhattan = shortestPath[from].manhattanDistance(shortestPath[end])
31
+ manhattan <= maxDistance && manhattan <= end - from - lim
32
+ }
38
33
}
39
- .groupBy { it }
40
- .filterKeys { it >= lim }
41
- .map { it.value.size }
42
- .sum()
43
34
}
44
35
45
-
46
- private tailrec fun bfs (
47
- start : Pos ,
48
- end : Pos ,
49
- queue : ArrayDeque <List <Pos >> = ArrayDeque (listOf(listOf(start))),
50
- visited : MutableSet <Pos > = mutableSetOf(start)
51
- ): List <Pos > {
52
- if (queue.isEmpty()) return emptyList()
53
- // Dequeue the current path
54
- val path = queue.removeFirst()
55
- val current = path.last()
56
-
57
- // Check if we reached the end position
58
- if (current == end) return path
59
- current.neighbourCellsUDLR()
60
- .filter { it !in visited }
61
- .filter { it in racetrack }
62
- .filter { racetrack[it] != ' #' }
63
- .forEach { neighbor ->
64
- visited.add(neighbor)
65
- queue.add(path + neighbor) // Enqueue the new path
36
+ private fun getPath (): List <Pos > {
37
+ return mutableListOf (start).apply {
38
+ while (last() != end) {
39
+ add(
40
+ last()
41
+ .neighbourCellsUDLR()
42
+ .filter { racetrack[it] != ' #' }
43
+ .first { it != getOrNull(lastIndex - 1 ) }
44
+ )
66
45
}
67
- // Recursive call with the updated queue and visited set
68
- return bfs(start, end, queue, visited)
46
+ }
69
47
}
70
48
71
49
override fun List<String>.parse (): Pair <Array <CharArray >, Pair<Pos, Pos>> {
0 commit comments