From 2e21177633f2bc2883e7a71c3af0b17e17c74f60 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 21 Nov 2024 23:53:36 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2257.=20Count=20Unguarded=20C?= =?UTF-8?q?ells=20in=20the=20Grid=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/count-unguarded-cells-in-the-grid/ Signed-off-by: Matej Focko --- kt/count-unguarded-cells-in-the-grid.kt | 79 +++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 kt/count-unguarded-cells-in-the-grid.kt diff --git a/kt/count-unguarded-cells-in-the-grid.kt b/kt/count-unguarded-cells-in-the-grid.kt new file mode 100644 index 0000000..f513ae7 --- /dev/null +++ b/kt/count-unguarded-cells-in-the-grid.kt @@ -0,0 +1,79 @@ +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 } + } + } +}