kt: add «2257. Count Unguarded Cells in the Grid»
URL: https://leetcode.com/problems/count-unguarded-cells-in-the-grid/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9b0d6ca964
commit
2e21177633
1 changed files with 79 additions and 0 deletions
79
kt/count-unguarded-cells-in-the-grid.kt
Normal file
79
kt/count-unguarded-cells-in-the-grid.kt
Normal file
|
@ -0,0 +1,79 @@
|
|||
class Solution {
|
||||
private fun <A, B> product(
|
||||
xs: Sequence<A>,
|
||||
ys: Sequence<B>,
|
||||
): Sequence<Pair<A, B>> = xs.flatMap { x -> ys.map { y -> x to y } }
|
||||
|
||||
private fun <A, B> product(
|
||||
xs: Iterable<A>,
|
||||
ys: Iterable<B>,
|
||||
): Sequence<Pair<A, B>> = product(xs.asSequence(), ys.asSequence())
|
||||
|
||||
private enum class State {
|
||||
Unguarded,
|
||||
Guarded,
|
||||
Guard,
|
||||
Wall,
|
||||
}
|
||||
|
||||
private fun update(
|
||||
grid: MutableList<MutableList<State>>,
|
||||
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<IntArray>,
|
||||
walls: Array<IntArray>,
|
||||
): 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..<m, listOf(0..<n, (0..<n).reversed())).forEach { (y, direction) ->
|
||||
direction.fold(false) { isGuardLineActive, x ->
|
||||
update(grid, y, x, isGuardLineActive)
|
||||
}
|
||||
}
|
||||
|
||||
// Process vertically
|
||||
product(0..<n, listOf(0..<m, (0..<m).reversed())).forEach { (x, direction) ->
|
||||
direction.fold(false) { isGuardLineActive, y ->
|
||||
update(grid, y, x, isGuardLineActive)
|
||||
}
|
||||
}
|
||||
|
||||
return grid.sumOf { row ->
|
||||
row.count { it == State.Unguarded }
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue