class Solution {
private fun product(
xs: Sequence,
ys: Sequence,
): Sequence> = xs.flatMap { x -> ys.map { y -> x to y } }
private fun product(
xs: Iterable,
ys: Iterable,
): Sequence> = product(xs.asSequence(), ys.asSequence())
private enum class State {
Unguarded,
Guarded,
Guard,
Wall,
}
private fun update(
grid: MutableList>,
y: Int,
x: Int,
guarded: Boolean,
): Boolean =
when (grid[y][x]) {
State.Guard -> true
State.Wall -> false
else -> {
if (guarded) {
grid[y][x] = State.Guarded
}
guarded
}
}
fun countUnguarded(
m: Int,
n: Int,
guards: Array,
walls: Array,
): Int {
// Initialize grid
val grid =
MutableList(m) {
MutableList(n) { State.Unguarded }
}
// Place guards
for (guard in guards) {
val (y, x) = guard[0] to guard[1]
grid[y][x] = State.Guard
}
// Place walls
for (wall in walls) {
val (y, x) = wall[0] to wall[1]
grid[y][x] = State.Wall
}
// Process horizontally
product(0..
direction.fold(false) { isGuardLineActive, x ->
update(grid, y, x, isGuardLineActive)
}
}
// Process vertically
product(0..
direction.fold(false) { isGuardLineActive, y ->
update(grid, y, x, isGuardLineActive)
}
}
return grid.sumOf { row ->
row.count { it == State.Unguarded }
}
}
}