And the minimum path - Dynamic Programming

Given a non-negative integer m * n grid, find a path from left to bottom right of the path so that the digital sum to a minimum.

Note: you can only move it to the right or down.

Example:

Input: 
[ 
  [ 1 , 3 , 1 ], 
  [ 1 , 5 , 1 ], 
  [ 4 , 2 , 1 ] 
] 
Output: 7 
explained: since the path 13111 the smallest sum.

 

Solution one: Dynamic Programming

thought

In doing because of the recent topics of dynamic programming, so with the idea of dynamic programming to solve this subject:
we create a dp array used to save the shortest path at every step, but the last value is the last element is definitely yes;
we use the recursive formula:
dp (i, J) = Grid (i, J) + min (dp (i + 1, J), dp (i, J + 1))
can be, and rather special, but found after the law was well understood.

Code

public int minPathSum(int[][] grid) {
    
    int[][] dp = new int[grid.length][grid[0].length];
    for (int i = grid.length - 1; i >= 0; i--) {
        for (int j = grid[0].length - 1; j >= 0; j--) {
            if(i == grid.length - 1 && j != grid[0].length - 1)
              dp[i][j] = grid[i][j] +  dp[i][j + 1];
            else if(j == grid[0].length - 1 && i != grid.length - 1)
              dp[i][j] = grid[i][j] + dp[i + 1][j];
            else if(j != grid[0].length - 1 && i != grid.length - 1)
              dp[i][j] = grid[i][j] + Math.min(dp[i + 1][j], dp[i][j + 1]);
            else
              dp[i][j] = grid[i][j];
        }
    }
    return dp[0][0];
}

operation result

 

These are the dynamic programming solution to the shortest path and, in the future the development process, when talked about an idea algorithm, can be used to change the subject, will add a new solution (because I am currently doing dynamic programming topics), hope we help !!!

Guess you like

Origin www.cnblogs.com/guohai-stronger/p/11881012.html