Given an m x n grid filled with non-negative numbers, find a path from the top-left cell to the bottom-right cell that minimizes the sum of all numbers along its path, and return that sum.
You can only move either down or right at any point in time.
Function Signature
def min_path_sum(grid: list[list[int]]) -> int:
Rules
-
The path starts at
grid[0][0]
and ends at
grid[m - 1][n - 1]
, and both of those cells count toward the sum.
-
Return only the minimum sum, not the path itself.
Constraints
-
m == len(grid)
-
n == len(grid[i])
-
1 <= m, n <= 200
-
0 <= grid[i][j] <= 200
Examples
Input: grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
Output: 7
The path 1 -> 3 -> 1 -> 1 -> 1 (right, right, down, down) sums to 7, and no other right/down path is cheaper.
Input: grid = [[1, 2, 3], [4, 5, 6]]
Output: 12
The path 1 -> 2 -> 3 -> 6 sums to 12. The other paths go through 4 or 5 in the bottom row and cost 13 or more.
Input: grid = [[1, 2], [1, 1]]
Output: 3
Going down first gives 1 -> 1 -> 1 = 3, while going right first gives 1 -> 2 -> 1 = 4.