Minimum Path Sum Problem
Description
LeetCode Problem 64.
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 200
- 0 <= grid[i][j] <= 100
Solution
Approach: Dynamic Programming with One Row
A path reaches a cell either from above or from the left, so the cheapest path to it costs the cell's own value plus the cheaper of those two:
best(row, col) = grid[row][col] + min(best(row - 1, col), best(row, col - 1)).
A greedy walk that always steps to the smaller neighbor does not work: a cheap step now can lead into expensive cells later, which is why we compute the best cost to every cell.
Only the previous row is needed, so keep one array best of length n:
- Start with
best[0] = 0and every other entry infinity. This acts like a row above the grid that can only be entered at the start. - For each row:
best[0] += row[0], because the first column can only be reached from above. Then forcolfrom 1 ton - 1,best[col] = min(best[col], best[col - 1]) + row[col]. Herebest[col]still holds the cell above andbest[col - 1]is the cell to the left, already updated for this row. - The answer is
best[n - 1]after the last row.
On the first row the infinities make every cell take the path from the left, so the first row and column need no special case.
Complexity: O(m · n) time and O(n) space, where m and n are the grid's height and width.
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
n = len(grid[0])
# best[col] = smallest sum of a path to column col of the current row.
# Before the first row nothing is reachable, except "above" the start, which costs 0.
best = [float("inf")] * n
best[0] = 0
for row in grid:
best[0] += row[0] # the first column can only be reached from above
for col in range(1, n):
# best[col] still holds the cell above; best[col - 1] is the cell to the left.
best[col] = min(best[col], best[col - 1]) + row[col]
return best[n - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.