Minimum Path Sum
Description:
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.
Code:
class Solution:
"""
@param grid: a list of lists of integers
@return: An integer, minimizes the sum of all numbers along its path
"""
def minPathSum(self, grid):
# write your code here
m = len(grid)
if m==1:
return sum(grid[0])
if m==0:
return 0
n = len(grid[0])
for i in range(1,m):
grid[i][0] += grid[i-1][0]
for j in range(1,n):
grid[0][j] += grid[0][j-1]
for i in range(1,m):
for j in range(1,n):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[m-1][n-1]