简体   繁体   中英

minimum cost path in matrix

Question -

Given amxn 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

I know this is a common question and most of you guys would know the question as well as its dynamic programming. I am trying the recursive code here but I am getting the correct output. what is missing in my recursive code? I don't want the iterative or dynamic programming approach. I am trying to build on my own.

It shows incorrect output.

Example -

1 2
1 1

It gives the output as 2. where as the answer is 3.

Thanks.

def minPathSum(self, grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """
    def helper(i,j,grid,dp):
        if i >= len(grid) or j >= len(grid[0]):
            return 0
        print grid[i][j]

        return grid[i][j]+min(helper(i+1,j,grid,dp),helper(i,j+1,grid,dp))
    dp = [[0] * len(grid[0]) for i in range(len(grid))]
    val = helper(0,0,grid,dp)
    print dp
    return val

I don't think it's correct to return 0 when you fall off the edge of the grid. That makes it look like you've succeeded. So I think the 2 that you are erroneously reporting is the 1 in upper left plus the 1 in lower left, followed by a "successful" falling off the bottom of the grid. I recommend you adjust your what-to-return logic so it looks like this:

if at right or bottom edge:
  there is only one direction to go, so
  return the result of going in that direction
else you do have options, so
  return the minimum of the two choices, like you do now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM