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.
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
2-dimensional dynamic programming array.
classSolution:defminPathSum(self,grid: List[List[int]]) ->int:ifnot grid orlen(grid)==0:return0# get dimensions n =len(grid)# no of cells in each col m =len(grid[0])# no of cells in each row# populate first row using m for no of cells in rowfor i inrange(1,m): grid[0][i] = grid[0][i] + grid[0][i-1]# populate first col using n for no of cells in colfor j inrange(1,n): grid[j][0] = grid[j-1][0] + grid[j][0]# populate the restfor i inrange(1,n):for j inrange(1,m):# get min seen so far plus curr cell value grid[i][j] =min(grid[i-1][j],grid[i][j-1])+ grid[i][j]# return last cellreturn grid[-1][-1]
We're going to take the big problem we have of going from the top left hand corner to the bottom right hand corner and break that into smaller subproblems.
Let's try going from the top left hand corner to the top right hand corner. If we can calculate the smallest sum to get to any sum on our grid, we can do it to the bottom right hand corner.
Mirror our grid and store the smallest sum to get to that specific square.