Skip to content

Commit

Permalink
Try reducing duplicate work
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient committed Dec 16, 2023
1 parent 1137017 commit c366bba
Showing 1 changed file with 30 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.github.ephemient.aoc2023
class Day16(input: String) {
private val input = input.lines().filter { it.isNotEmpty() }

private fun fill(y: Int, x: Int, d: Direction): Int {
private fun fill(y: Int, x: Int, d: Direction, todo: MutableSet<Pair<IntPair, Direction>>): Int {
val stack = mutableListOf(y to x to d)
val visited = stack.toMutableSet()
while (true) {
Expand All @@ -13,23 +13,45 @@ class Day16(input: String) {
if (p2.first in input.indices && p2.second in input[p2.first].indices) {
val next = p2 to d2
visited.add(next) && stack.add(next)
} else {
todo.remove(p1 to -d1)
}
}
}
return visited.mapTo(mutableSetOf()) { it.first }.size
}

fun part1(): Int = fill(0, 0, Direction.R)
fun part1(): Int = fill(0, 0, Direction.R, mutableSetOf())

fun part2(): Int = maxOf(
input.indices.maxOf { fill(it, 0, Direction.R) },
input.first().indices.maxOf { fill(0, it, Direction.D) },
input.indices.maxOf { fill(it, input[it].lastIndex, Direction.L) },
input.last().indices.maxOf { fill(input.lastIndex, it, Direction.U) },
)
fun part2(): Int {
var max = 0
val todo = mutableSetOf<Pair<IntPair, Direction>>()
for (x in 0..input.first().lastIndex) todo.add(0 to x to Direction.D)
for ((y, line) in input.withIndex()) {
todo.add(y to 0 to Direction.R)
todo.add(y to line.lastIndex to Direction.L)
}
for (x in 0..input.last().lastIndex) todo.add(input.lastIndex to x to Direction.U)
while (true) {
val iterator = todo.iterator()
if (!iterator.hasNext()) break
val (pos, d) = iterator.next()
iterator.remove()
max = maxOf(max, fill(pos.first, pos.second, d, todo))
}
return max
}

private enum class Direction {
U, L, D, R,
;

operator fun unaryMinus(): Direction = when (this) {
U -> D
L -> R
D -> U
R -> L
}
}

companion object {
Expand Down

0 comments on commit c366bba

Please sign in to comment.