You are given a m x n 2D integer array grid and an integer k. You start at the top-left cell (0, 0) and your goal is to reach the bottomβright cell (m - 1, n - 1).
There are two types of moves available:
Normal move: You can move right or down from your current cell (i, j), i.e. you can move to (i, j + 1) (right) or (i + 1, j) (down). The cost is the value of the destination cell.
Teleportation: You can teleport from any cell (i, j), to any cell (x, y) such that grid[x][y] <= grid[i][j]; the cost of this move is 0. You may teleport at most k times.
Return the minimum total cost to reach cell (m - 1, n - 1) from (0, 0).
Β
Example 1:
Input:grid = [[1,3,3],[2,5,4],[4,3,5]], k = 2
Output:7
Explanation:
Initially we are at (0, 0) and cost is 0.
Current Position
Move
New Position
Total Cost
(0, 0)
Move Down
(1, 0)
0 + 2 = 2
(1, 0)
Move Right
(1, 1)
2 + 5 = 7
(1, 1)
Teleport to (2, 2)
(2, 2)
7 + 0 = 7
The minimum cost to reach bottom-right cell is 7.
Example 2:
Input:grid = [[1,2],[2,3],[3,4]], k = 1
Output:9
Explanation:
Initially we are at (0, 0) and cost is 0.
Current Position
Move
New Position
Total Cost
(0, 0)
Move Down
(1, 0)
0 + 2 = 2
(1, 0)
Move Right
(1, 1)
2 + 3 = 5
(1, 1)
Move Down
(2, 1)
5 + 4 = 9
The minimum cost to reach bottom-right cell is 9.
Β
Constraints:
2 <= m, n <= 80
m == grid.length
n == grid[i].length
0 <= grid[i][j] <= 104
0 <= k <= 10
Solutions
Solution 1: Dynamic Programming
We define \(f[t][i][j]\) as the minimum cost to reach cell \((i, j)\) using exactly \(t\) teleportations. Initially, \(f[0][0][0] = 0\), and all other states are infinity.
First, we need to initialize \(f[0][i][j]\). Without using teleportation, we can only reach cell \((i, j)\) by moving right or down.
If \(i > 0\), we can move from the cell above \((i-1, j)\), updating the state as:
To handle teleportation, we need to group the cells in the grid by their values. We use a hash map \(g\), where the key is the cell value and the value is a list of coordinates of cells with that value.
For each teleportation count \(t\) from \(1\) to \(k\), we process each group in descending order of cell values. For each cell \((i, j)\) in a group, we first update a global minimum \(mn\), representing the minimum cost to reach these cells using \(t-1\) teleportations:
\[mn = \min(mn, f[t-1][i][j])\]
Then, we update the state of all cells in the group to \(mn\), representing the minimum cost to reach these cells via teleportation.
Next, we traverse the entire grid again to update \(f[t][i][j]\), considering moves from the top or left cells:
Finally, our answer is \(\min(f[t][m-1][n-1])\), where \(t\) ranges from \(0\) to \(k\).
The time complexity is \(O((k + \log mn) \times mn)\), and the space complexity is \(O(k \times mn)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, respectively, and \(k\) is the maximum allowed number of teleportations.