#2304
Minimum Path Cost in a Grid
MediumArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(m * n²)Space O(n)
Using dynamic programming, we can build up the minimum cost for each cell in the grid row by row, avoiding redundant calculations and significantly reducing the number of operations.
⚙️
Algorithm
4 steps- 1Step 1: Create a DP array to store the minimum cost to reach each cell in the current row.
- 2Step 2: Initialize the first row of the DP array with the values from the grid.
- 3Step 3: For each subsequent row, calculate the minimum cost for each cell based on the previous row's DP values and the move costs.
- 4Step 4: Return the minimum value from the last row of the DP array.
solution.py14 lines
1# Full working Python code
2from typing import List
3
4
5def minPathCost(grid: List[List[int]], moveCost: List[List[int]]) -> int:
6 m, n = len(grid), len(grid[0])
7 dp = grid[0][:]
8 for row in range(1, m):
9 new_dp = [float('inf')] * n
10 for col in range(n):
11 for next_col in range(n):
12 new_dp[next_col] = min(new_dp[next_col], dp[col] + moveCost[grid[row - 1][col]][next_col] + grid[row][next_col])
13 dp = new_dp
14 return min(dp)ℹ
Complexity note: The time complexity is O(m * n²) because for each row (m), we iterate through each cell (n) and check all possible next cells (n) for the minimum cost.
- 1Dynamic programming helps avoid redundant calculations.
- 2Understanding the cost structure is crucial for efficient pathfinding.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.