Minimum Cost Path With At Most K Turns Problem
Description
LeetCode Problem 4046.
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:
- An optimal path is (0, 0) → (1, 0) → (1, 1) → (1, 2). The moves are down, right, right.
- The direction changes from down to right once, so the path uses exactly k = 1 turn.
- The total path cost is 2 + 1 + 4 + 5 = 12.
Example 2:
Input: grid = [[4,1,9],[3,2,5],[4,8,6]], k = 2
Output: 20
Explanation:
- An optimal path is (0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2). The moves are down, right, right, down.
- The direction changes from down to right and from right to down, so the path uses exactly k = 2 turns.
- The total path cost is 4 + 3 + 2 + 5 + 6 = 20.
Example 3:
Input: grid = [[1,9],[3,4]], k = 0
Output: -1
Explanation:
- It is impossible to reach (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)
Solution
Approach: Dynamic Programming by Number of Turns
A path is a walk in which the cells may repeat, so we track the last move direction and the turns used. Let dp[t][d][i][j] be the cheapest cost of a walk that ends at (i, j) after a move in direction d, using exactly t turns (the cost of the start cell is added at the end).
A move into (i, j) in direction d comes from the previous cell (i - di, j - dj), and either:
- continues straight:
dp[t][d][prev], from the same layert, or - turns:
dp[t - 1][e][prev]for any other directione != d.
In layer 0 the first move out of the start cell is free of turns. Inside one layer and direction, cells depend only on the cell just behind them, so processing the rows (or columns) in the direction of travel fills the layer in order. There are no cycles, so no priority queue is needed. The answer is the minimum over all layers t <= k and directions of the value at (m - 1, n - 1) plus grid[0][0], or -1 if it is unreachable. A 1 x 1 grid is just grid[0][0].
Complexity: O(k * m * n) time and O(m * n) space, since only the previous layer is kept.
class Solution:
def minCost(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
if m == 1 and n == 1:
return grid[0][0]
inf = float('inf')
# the cells of every straight line, in the order a move in direction d walks them
lines = [
[[(i, j) for i in range(m)] for j in range(n)], # down
[[(i, j) for i in range(m - 1, -1, -1)] for j in range(n)], # up
[[(i, j) for j in range(n)] for i in range(m)], # right
[[(i, j) for j in range(n - 1, -1, -1)] for i in range(m)], # left
]
# cur[d][i][j]: cheapest walk that ends in (i, j) after a move in direction d with exactly t turns
prev = None
ans = inf
for t in range(k + 1):
if t == 0:
# only the start (0, 0) can begin a straight run
start = [[inf] * n for _ in range(m)]
start[0][0] = 0
into = [start] * 4
else:
# turning into direction d: the best walk that ended with any other direction
into = []
for d in range(4):
a, b, c = [prev[e] for e in range(4) if e != d]
into.append([list(map(min, ra, rb, rc)) for ra, rb, rc in zip(a, b, c)])
cur = []
for d in range(4):
res = [[inf] * n for _ in range(m)]
src = into[d]
for line in lines[d]:
run = inf # best value standing on the previous cell of this line
for i, j in line:
if run < inf:
res[i][j] = run + grid[i][j]
run = min(res[i][j], src[i][j])
cur.append(res)
for d in range(4):
ans = min(ans, cur[d][m - 1][n - 1])
prev = cur
return -1 if ans == inf else ans + grid[0][0]