Problem Description
Given an m x n grid of distinct integers and a moveCost matrix, the task is to find the minimum path cost starting from any cell in the first row and ending at any cell in the last row. You may move from a cell (x, y) to any cell in the next row, incurring a movement cost specified in moveCost. The total cost is the sum of visited cell values and the corresponding move costs.
Key Insights
- Use Dynamic Programming to keep track of minimum costs reaching each cell.
- Use a 2D DP table (or 1D array optimization) where dp[i][j] represents the minimum cost reaching cell (i, j).
- Transition from row i to row i+1 by considering every column move and adding the cost of movement.
- The solution requires iterating row by row, and for each cell, checking all possible moves to the next row.
Space and Time Complexity
Time Complexity: O(m * n^2) where for each row (m) we consider n possible starting columns and for each we examine n possible moves. Space Complexity: O(m * n) for the DP table (can be optimized to O(n) using two arrays).
Solution
We solve this problem using dynamic programming. Initialize a dp array representing the costs of starting from the first row (which are simply the cell values). For each subsequent row, compute a new dp array where each element dp_next[j] for cell (i+1, j) is the minimum over all possible moves from any cell in the previous row i of (current cost + move cost from that cell to column j + value at grid[i+1][j]). After processing all rows, the answer will be the minimum value in the last computed dp array. The key trick is to consider the moveCost using the grid value as an index to access the additional cost to move to a particular column.