[Dynamic programming] Minimum path with weights and

In fact, this problem is a fusion version of the triangular matrix and the path. Knowing the solution to the first two problems, the minimum path sum with weights can be directly won.
Triangular Matrix Link

find path link

insert image description here

Bull link

Question: Given a 2D array of mxn filled with non-negative integers, now you want to go from the upper left corner to the lower right corner of the 2D array, find the path with the smallest sum of all numbers on the path.
Note: You can only move down or right at a time.

Analysis idea: In fact, the idea of ​​​​this question is to find the shortest path sum from the coordinates (0, 0) to the coordinates (i, j). The coordinates (0, j) of the first line can only be used by (0, j-1) The coordinates are obtained by moving one step to the right, and the coordinates (i, 0) of the first column can only be obtained by moving the coordinates (i-1, 0) down one step. The states of these two coordinates are added to their own path weights. The weight of the coordinate to move to this coordinate in one step. Other coordinates (i, j) can be obtained by moving the coordinates (i-1, j) down or the coordinates (i, j-1) to the right, so its state is its own path weight plus these two moves The state of the coordinate with the smaller path weight in the mode. The last thing returned is the weight status of the coordinates of the lower right corner.

insert image description here

In summary:

Four angles of dynamic programming:

  1. State definition F(i, j): the sum of the shortest paths from coordinates (0, 0) to coordinates (i, j);
  2. The transition equation between states is defined:
  • i == 0,F(0,j) = F(0,j-1) + grid[0][j];
  • j == 0,F(i,0) = F(i-1,0) + grid[i][0];
  • 其余,F(i,j) = min(F(i-1,j),F(i,j-1)) + grid[i][j];
  1. State initialization F(0, 0) = grid[0][0];
  2. Return the result F(row-1, col-1);
import java.util.*;
public class Solution {
    
    
    public int minPathSum (int[][] grid) {
    
    
        int row = grid.length;//行
        int col = grid[0].length;//列
        if(row == 0 && col == 0) return 0;
        //第一列状态转移
        for(int i = 1;i < row;i ++) {
    
    
            grid[i][0] = grid[i-1][0] + grid[i][0];
        }
        //第一行状态转移
        for(int j = 1;j < col;j ++) {
    
    
            grid[0][j] = grid[0][j-1] + grid[0][j];
        }
        //其余坐标状态转移
        for(int i = 1;i < row;i++) {
    
    
            for(int j = 1;j < col;j++) {
    
    
                grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
            }
        }
        return grid[row-1][col-1];//返回结果
    }
}

Finish!

Guess you like

Origin blog.csdn.net/weixin_46103589/article/details/121948015
Recommended