Minimum Cost Path With At Most K Turns solution and explanation
4 more videos on this problem
Leetcode Weekly Contest 518 | Q4 - Minimum Cost Path With At Most K Turns | 4046 | GRAPH + DPKumar K [Amazon] · 49:23 · 846 views
Leetcode 4046 | Minimum Cost Path With At Most K Turns | Leetcode weekly contest 518CodeWithMeGuys · 17:08 · 177 views
LeetCode 4046: Minimum Cost Path With At Most K Turns | Dijkstra + State DP | Biweekly Contest 190EdgeCaseOffByOne · 18:59 · 131 views
Minimum Cost Path With At Most K Turns | Dijkstra's with state transition | Leetcode 4046Manjeet Dhayal · 15:46 · 88 views
Weekly Contest 518 Q4 | LeetCode 4046 | Minimum Cost Path With At Most K Turn | Dijkstra + DP | HardCode With Logic · 35:28 · 9 views
The problem
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 = 1turn. - 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 = 2turns. - 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)usingk = 0turns. Thus, the answer is -1.
Constraints:
1 <= m == grid.length <= 751 <= n == grid[i].length <= 750 <= grid[i][j] <= 10000 <= k < min(m, n)
Approach overview
Problem Overview: You are given an m x n grid where each cell has a cost, and you need to travel from (0,0) to (m-1,n-1) using up, down, left, or right moves. The path can contain at most K turns (a turn is a direction change). Find the minimum total cost of such a path, including the cost of the starting and ending cells.
Approach 1: Brute Force DFS with Backtracking (Exponential Time)
Enumerate every possible path using recursive DFS. Carry the current cell, the current direction, and the number of turns used so far. At each step try all four moves. When moving in a direction different from the current direction, increment the turn count. Prune any branch where the turn count exceeds K or you step off the grid. This explores all paths, leading to O(4^(m*n)) time and O(m*n) recursion stack. It is only practical for very small grids, but it is useful to verify the correctness of an optimal algorithm on test cases.
Approach 2: Dijkstra's Algorithm on a State Graph (Optimal, O(m*n*K*4 log(m*n*K*4)))
The key insight is that the total cost to reach a specific cell is not enough — the direction you arrived from and how many turns you have already used affect future moves. So model the problem as a shortest path on a state graph where each node is (row, col, direction, turnsUsed). There are 4 possible directions and 0..K turn counts, giving m*n*4*(K+1) states. An edge from a state to a neighboring cell has a cost equal to the neighbor's cell value; if moving in the same direction the turn count stays the same, otherwise it increments by 1. Skip transitions where the new turn count exceeds K.
Use a min-heap (priority queue) to always expand the lowest-cost state, similar to standard Dijkstra. Initialize the start cell with all four directions and turnsUsed = 0 (since there is no previous direction, you can start in any direction for free). When you pop a state that reaches the destination, the heap guarantee means you have found the minimum cost. Alternatively, you can track the minimum cost to each state in a 4D distance array and when the destination is popped for the first time, return the cost.
Because cell costs are non-negative, Dijkstra is correct. The time complexity is O(m*n*K*4 log(m*n*K*4)) because each state is pushed and popped at most once. The space complexity is O(m*n*K*4) for the distance array plus the heap overhead in the worst case.
Approach 3: Why Standard DP Does Not Work Here
You might think a flat m x n DP table would solve this, but the turn constraint and ability to move in all four directions create cycles. A classic DP requires a topological order, which does not exist in an undirected grid with positive costs. Dijkstra avoids this by relaxing states multiple times and using a global priority criterion.
Recommended for interviews: Explain the brute-force DFS first to demonstrate your understanding of the state space. Then present the Dijkstra state-graph solution. The moment you say “the state must include the direction and the number of turns used” is the moment interviewers know you have solved similar graph problems. Mention the 4D distance array and the min-heap explicitly. The brute force shows fundamentals; the Dijkstra solution shows mastery of shortest-path algorithms under constraints. For more practice, explore related problems in the graph topic and the shortest path collection. You can also review heap-based algorithms for other pathfinding problems.
The written solution for this problem is still being prepared. Try it yourself in the meantime.
Try solving it yourselfComplexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force DFS + Backtracking | O(4^(m*n)) | O(m*n) | Only for tiny grids or verification of brute force against optimal |
Dijkstra on State Graph (row, col, dir, turns) | O(m*n*K*4 log(m*n*K*4)) | O(m*n*K*4) | General case with arbitrary non-negative costs; the standard interview solution |
Frequently asked questions
Is Minimum Cost Path With At Most K Turns easy or hard?
It is a hard problem. The 53.9% acceptance rate suggests that while the concept is approachable, correctly encoding the turn count into Dijkstra's state is easy to mess up. It shows the interviewer that you can expand classic algorithms to handle additional constraints.
Minimum Cost Path With At Most K Turns Python/Java solution
In Python use `heapq` and in Java use `PriorityQueue` to implement the Dijkstra state graph. Start from (0,0) with all four initial directions, relax neighbors, and increment the turn count only when the direction changes. Return the first popped destination state.
How to solve Minimum Cost Path With At Most K Turns in O(n)?
There is no O(n) or O(m*n) solution for the general problem because the state space is inherently 4-dimensional. The Dijkstra approach is effectively near-linear in the number of states, O(m*n*K*4 log(m*n*K*4)), which is optimal for non-negative arbitrary weights.
What is the best approach for Minimum Cost Path With At Most K Turns?
The best approach is Dijkstra's algorithm on an augmented state graph where each state is (row, col, direction, turnsUsed). This correctly handles the turn constraint while working with arbitrary non-negative cell costs. It runs in O(m*n*K*4 log(m*n*K*4)) time and O(m*n*K*4) space.
Is Minimum Cost Path With At Most K Turns asked at Google/Amazon/Meta?
Yes, this is a known hard graph problem that appears in interviews at companies like Google, Amazon, and Meta. The core skill tested is transforming a stateful constraint into a shortest-path graph and then applying Dijkstra correctly.
What data structure is used in Minimum Cost Path With At Most K Turns?
A priority queue (min-heap) is essential. Each entry stores the current total cost and a state tuple (row, col, direction, turnsUsed). You also need a 4D distance array to track the best cost reached for each state.
What is the time complexity of Minimum Cost Path With At Most K Turns?
The optimal Dijkstra-based solution has time complexity O(m*n*K*4 log(m*n*K*4)) and space complexity O(m*n*K*4). Brute-force DFS is exponential at O(4^(m*n)), so it is unusable for real inputs.
