Minimum Path Cost in a Grid - Problem
Problem: Find the Minimum Path Cost in a Grid
Imagine you're navigating through a special grid maze where you can only move downward from one row to the next, but you have the freedom to choose any column in the next row!
Given:
• An
• A
Movement Rules:
• From cell
• You cannot move from the last row (it's your destination!)
Goal: Find the minimum total cost path from any cell in the first row to any cell in the last row. The total cost includes both the cell values you visit plus the movement costs between cells.
This is a classic dynamic programming problem that tests your ability to optimize multi-dimensional decision making!
Imagine you're navigating through a special grid maze where you can only move downward from one row to the next, but you have the freedom to choose any column in the next row!
Given:
• An
m x n integer matrix grid with distinct values from 0 to m * n - 1• A
moveCost array where moveCost[i][j] represents the cost of moving from a cell with value i to column j in the next rowMovement Rules:
• From cell
(x, y), you can move to any cell (x+1, 0), (x+1, 1), ..., (x+1, n-1)• You cannot move from the last row (it's your destination!)
Goal: Find the minimum total cost path from any cell in the first row to any cell in the last row. The total cost includes both the cell values you visit plus the movement costs between cells.
This is a classic dynamic programming problem that tests your ability to optimize multi-dimensional decision making!
Input & Output
example_1.py — Basic 3x3 Grid
$
Input:
grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[8,4],[1,3],[2,7]]
›
Output:
8
💡 Note:
The optimal path is (0,1) → (1,1) → (2,1). Cost = 3 + moveCost[3][1] + 0 + moveCost[0][1] + 1 = 3 + 4 + 0 + 8 + 1 = 16. Actually, let me recalculate: path (0,1) → (1,1) → (2,0): cost = 3 + moveCost[3][1] + 0 + moveCost[0][0] + 2 = 3 + 4 + 0 + 9 + 2 = 18. The minimum path is (0,0) → (1,1) → (2,0): cost = 5 + moveCost[5][1] + 0 + moveCost[0][0] + 2 = 5 + 7 + 0 + 9 + 2 = 23. Wait, let me verify all paths systematically...
example_2.py — Simple 2x2 Grid
$
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
💡 Note:
The optimal path is (0,1) → (1,1). Cost = 1 + moveCost[1][1] + 0 = 1 + 5 + 0 = 6.
example_3.py — Single Column Edge Case
$
Input:
grid = [[1],[2],[3]], moveCost = [[2],[3],[1]]
›
Output:
6
💡 Note:
Only one possible path: (0,0) → (1,0) → (2,0). Cost = 1 + moveCost[1][0] + 2 + moveCost[2][0] + 3 = 1 + 3 + 2 + 1 + 3 = 10. Let me recalculate: 1 + 2 + 2 + 3 + 3 = 11. Actually: 1 + 3 + 2 + 1 + 3 = 10.
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
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code