From f878952bbcb93d48850d9e20b1570c2a6bf32da0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 29 Nov 2024 22:09:20 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2290.=20Minimum=20Obstacle=20?= =?UTF-8?q?Removal=20to=20Reach=20Corner=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/ Signed-off-by: Matej Focko --- ...inimum-obstacle-removal-to-reach-corner.kt | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 kt/minimum-obstacle-removal-to-reach-corner.kt diff --git a/kt/minimum-obstacle-removal-to-reach-corner.kt b/kt/minimum-obstacle-removal-to-reach-corner.kt new file mode 100644 index 0000000..81dc76e --- /dev/null +++ b/kt/minimum-obstacle-removal-to-reach-corner.kt @@ -0,0 +1,54 @@ +class Solution { + private data class Position(val x: Int, val y: Int) { + operator fun plus(rhs: Position): Position = Position(x + rhs.x, y + rhs.y) + } + + companion object { + private val DIRECTIONS = + listOf( + Position(0, 1), + Position(0, -1), + Position(1, 0), + Position(-1, 0), + ) + } + + private fun isValid( + grid: Array, + p: Position, + ): Boolean = + ( + p.y >= 0 && p.y < grid.size && p.x >= 0 && p.x < grid[p.y].size + ) + + fun minimumObstacles(grid: Array): Int { + val (rows, cols) = grid.size to grid[0].size + + val dp = Array(rows) { IntArray(cols) { Int.MAX_VALUE } } + dp[0][0] = 0 + + val deque = ArrayDeque>() + deque.addLast(Position(0, 0) to 0) + + while (!deque.isEmpty()) { + val (position, obstacles) = deque.removeFirst() + + DIRECTIONS.forEach { dir -> + val next = position + dir + if (!isValid(grid, next) || dp[next.y][next.x] != Int.MAX_VALUE) { + return@forEach + } + + if (grid[next.y][next.x] == 1) { + dp[next.y][next.x] = obstacles + 1 + deque.addLast(next to obstacles + 1) + } else { + dp[next.y][next.x] = obstacles + deque.addFirst(next to obstacles) + } + } + } + + return dp[rows - 1][cols - 1] + } +}