Programmer upgrade Daguai level 5: How many ways does the robot have to reach the end?

Hi everyone, I am "@不飞的小飞驴"

5 Different paths for the robot to go to the end point
A robot is located in the upper left corner of an mxn grid (the starting point is marked as "Start" in the figure below).
The robot can only move one step down or to the right at a time. The robot tries to reach the bottom right corner of the grid (marked "Finish" in the image below).
How many different paths are there in total?

Example 1:
Insert picture description here

Input: m=3, n=7
Output: 28

Example 2:
Input: m = 3, n = 2
Output: 3
Explanation:
Starting from the upper left corner, there are a total of 3 paths to the lower right corner.

  1. Right -> down -> down
  2. Down -> right -> down
  3. Down -> down -> right

First of all, think about what is a good way. Welcome to comment below.

Overall thinking: The main idea used in this question is: dynamic programming solution.
Note that the robot can only move down and to the right, and cannot move in other directions. We use dp[i][j] to indicate the coordinates (i, j) How many different paths are in this grid, so the final answer is to find dp[m-1][n-1].
Because it can only come from above or from the left, the recurrence formula is
dp[i][j]=dp[i-1][j]+dp[i][j-1].

dp[i-1][j] represents the number of paths from above.
dp[i][j-1] represents the number of paths from the left.
Insert picture description here

So what are the boundary conditions? If Finish has only one path at any position in the first row, and in the same way, Finish has only one path at any position in the first column, so the boundary condition is that the first row and the first column are both 1. We have found the recurrence formula and the boundary conditions, so the dynamic programming code is as follows:
Program:

public int uniquePaths(int m, int n) {
    
    
    int[][] dp = new int[m][n];
    //第一列都是1
    for (int i = 0; i < m; i++) {
    
    
        dp[i][0] = 1;
    }
    //第一行都是1
    for (int i = 0; i < n; i++) {
    
    
        dp[0][i] = 1;
    }

    //这里是递推公式
    for (int i = 1; i < m; i++)
        for (int j = 1; j < n; j++)
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
    return dp[m-1][n-1];
}

Guess you like

Origin blog.csdn.net/u014251610/article/details/113747805