minimum cost path in matrix
<p>Question -</p>

<p>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.</p>

<p>Note: You can only move either down or right at any point in time</p>

<p>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. </p>

<p>It shows incorrect output.</p>

<p>Example -</p>

<pre><code>1 2
1 1
</code></pre>

<p>It gives the output as 2. where as the answer is 3.</p>

<p>Thanks. </p>

<pre><code>def minPathSum(self, grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """
    def helper(i,j,grid,dp):
        if i &gt;= len(grid) or j &gt;= 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
</code></pre>

<p>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:</p>

<pre><code>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
</code></pre>

python algorithm dynamic