LeetCode Problem Workspace

Minimum Path Cost in a Grid

Minimize the cost of a path in a grid while considering move costs for each step.

category

3

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Medium · State transition dynamic programming

bolt

Answer-first summary

Minimize the cost of a path in a grid while considering move costs for each step.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for State transition dynamic programming

Try AiBox Copilotarrow_forward

The problem asks you to find the minimum path cost in a grid, where each move between rows has a specific cost. Using dynamic programming, you can optimize the solution by considering each possible move's cost while traversing the grid from top to bottom.

Problem Statement

You are given an m x n integer matrix grid where the integers range from 0 to m * n - 1. Starting from any cell in the first row, you can move to any cell in the next row. You are also given a 2D array moveCost where moveCost[i][j] represents the cost of moving from a cell with value i to a cell in column j of the next row. You cannot move from cells in the last row, and the goal is to find the minimum cost path that starts at any cell in the first row and ends at any cell in the last row.

The cost of the path is determined by the sum of all values in the cells visited plus the cost of the moves made between these cells. For example, if you move from a cell containing value 5 to a cell with value 0, the cost of the move is given by moveCost[5][0]. Your task is to calculate the minimum cost for any valid path from the first to the last row.

Examples

Example 1

Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]

Output: 17

The path with the minimum possible cost is the path 5 -> 0 -> 1.

  • The sum of the values of cells visited is 5 + 0 + 1 = 6.
  • The cost of moving from 5 to 0 is 3.
  • The cost of moving from 0 to 1 is 8. So the total cost of the path is 6 + 3 + 8 = 17.

Example 2

Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]

Output: 6

The path with the minimum possible cost is the path 2 -> 3.

  • The sum of the values of cells visited is 2 + 3 = 5.
  • The cost of moving from 2 to 3 is 1. So the total cost of this path is 5 + 1 = 6.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 50
  • grid consists of distinct integers from 0 to m * n - 1.
  • moveCost.length == m * n
  • moveCost[i].length == n
  • 1 <= moveCost[i][j] <= 100

Solution Approach

Dynamic Programming Approach

A dynamic programming approach is ideal for this problem, where we maintain a 2D dp array dp[x][y] that stores the minimum cost to reach cell (x, y) from any cell in the first row. We start by initializing the first row with the values from grid and then iteratively compute the minimum cost to reach each cell in the following rows by considering all possible moves from the previous row.

State Transition Logic

For each cell in row i (except the first row), we calculate the minimum cost to reach it by evaluating all the possible previous cells from row i-1. The cost to reach a cell is the cost of the current cell from the grid plus the cost of the move between rows, as defined by moveCost. This ensures we always select the least costly option for each step.

Final Computation

After filling out the dp table for all rows, the minimum cost to reach the last row will be the smallest value found in the last row of the dp table. This value will represent the optimal path cost.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

The time complexity is O(m * n * n) because, for each cell in each row, we evaluate n possible moves from the previous row. The space complexity is O(m * n) due to the dp table storing intermediate results for each cell in the grid.

What Interviewers Usually Probe

  • Look for candidates who can identify the need for dynamic programming in minimizing path costs.
  • Assess whether they understand state transitions and can apply them to this grid-based problem.
  • Evaluate if they can efficiently handle the computation and space requirements for dynamic programming.

Common Pitfalls or Variants

Common pitfalls

  • Not considering all possible moves from the previous row, leading to incorrect results.
  • Forgetting to handle edge cases, such as the last row where no further moves are possible.
  • Incorrectly calculating move costs between cells, potentially misinterpreting the moveCost matrix.

Follow-up variants

  • Consider variations where the grid size or moveCost matrix dimensions are different.
  • Introduce obstacles or forbidden cells in the grid and calculate the cost accordingly.
  • Change the problem to minimize the number of moves instead of cost, introducing a different dynamic programming approach.

FAQ

What is the key pattern for solving Minimum Path Cost in a Grid?

The key pattern is dynamic programming with state transitions. We calculate the minimum cost for each cell by considering the moves from the previous row.

How does dynamic programming apply in this problem?

Dynamic programming helps break the problem down into subproblems, where the minimum cost to reach each cell is calculated iteratively, ensuring optimality.

What is the role of the moveCost matrix?

The moveCost matrix defines the cost of moving from one cell to another between rows, and it is essential in calculating the total path cost.

How do I handle the constraints on grid size and moveCost?

You handle the constraints by designing an efficient dynamic programming solution that operates within the time and space limits, typically O(m * n * n).

Can GhostInterview assist with similar dynamic programming problems?

Yes, GhostInterview can provide tailored approaches for similar dynamic programming problems, helping you understand and implement efficient solutions.

terminal

Solution

Solution 1: Dynamic Programming

We define $f[i][j]$ to represent the minimum path cost from the first row to the $i$th row and $j$th column. Since we can only move from a column in the previous row to a column in the current row, the value of $f[i][j]$ can be transferred from $f[i - 1][k]$, where the range of $k$ is $[0, n - 1]$. Therefore, the state transition equation is:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        f = grid[0]
        for i in range(1, m):
            g = [inf] * n
            for j in range(n):
                for k in range(n):
                    g[j] = min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j])
            f = g
        return min(f)
Minimum Path Cost in a Grid Solution: State transition dynamic programming | LeetCode #2304 Medium