Hard
You are given a 2D integer array grid of size m x n, where grid[i][j] represents the cost of visiting cell (i, j), and an integer k.
You start at the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1).
From each cell, you may move one step in any of the four directions: up, down, left, or right.
The cost of a path is the sum of the values of all visited cells, including the starting and ending cells. If a cell is visited more than once, its value is included each time it is visited.
Return the minimum possible path cost to reach (m - 1, n - 1) using at most k turns. If no such path exists, return -1.
A turn occurs when the direction changes between two consecutive moves. For example, moving right and then down counts as one turn, while moving right and then right does not.
Example 1:
Input: grid = [[2,7,3],[1,4,5]], k = 1
Output: 12
Explanation:
(0, 0) → (1, 0) → (1, 1) → (1, 2). The moves are down, right, right.k = 1 turn.2 + 1 + 4 + 5 = 12.Example 2:
Input: grid = [[4,1,9],[3,2,5],[4,8,6]], k = 2
Output: 20
Explanation:
(0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2). The moves are down, right, right, down.k = 2 turns.4 + 3 + 2 + 5 + 6 = 20.Example 3:
Input: grid = [[1,9],[3,4]], k = 0
Output: -1
Explanation:
(1, 1) using k = 0 turns. Thus, the answer is -1.Constraints:
1 <= m == grid.length <= 751 <= n == grid[i].length <= 750 <= grid[i][j] <= 10000 <= k < min(m, n)import kotlin.math.min
class Solution {
fun minCost(grid: Array<IntArray>, k: Int): Int {
val m = grid.size
val n = grid[0].size
if (m == 1 && n == 1) {
return grid[0][0]
}
var entry: Array<LongArray> = Array<LongArray>(m) { LongArray(n) }
for (row in entry) {
row.fill(INF)
}
entry[0][0] = grid[0][0].toLong()
for (t in 0..k) {
val next: Array<LongArray> = Array<LongArray>(m) { LongArray(n) }
for (row in next) {
row.fill(INF)
}
for (i in 0..<m) {
var run: Long = INF
for (j in 1..<n) {
run = min(run, entry[i][j - 1]) + grid[i][j]
next[i][j] = min(next[i][j], run)
}
}
for (i in 0..<m) {
var run: Long = INF
for (j in n - 2 downTo 0) {
run = min(run, entry[i][j + 1]) + grid[i][j]
next[i][j] = min(next[i][j], run)
}
}
for (j in 0..<n) {
var run: Long = INF
for (i in 1..<m) {
run = min(run, entry[i - 1][j]) + grid[i][j]
next[i][j] = min(next[i][j], run)
}
}
for (j in 0..<n) {
var run: Long = INF
for (i in m - 2 downTo 0) {
run = min(run, entry[i + 1][j]) + grid[i][j]
next[i][j] = min(next[i][j], run)
}
}
entry = next
}
return if (entry[m - 1][n - 1] >= INF) -1 else entry[m - 1][n - 1].toInt()
}
companion object {
private val INF = 1e15.toLong()
}
}