[] 63. Unique Paths II LeetCode different path II (Medium) (JAVA)

[] 63. Unique Paths II LeetCode different path II (Medium) (JAVA)

Topic Address: https://leetcode-.com/problems/unique-paths-ii/

Subject description:

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

Subject to the effect

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Now consider the grid obstructions. So how many different paths from top left to bottom right corner there will be?

Problem-solving approach

1, dynamic programming, traversing from the back
2, encountered 1, skip, or put on the front and the values are added

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) return 0;
        int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
        dp[obstacleGrid.length - 1][obstacleGrid[0].length - 1] = 1;
        for (int i = obstacleGrid.length - 1; i >= 0; i--) {
            for (int j = obstacleGrid[0].length - 1; j >= 0; j--) {
                if (obstacleGrid[i][j] == 1) continue;
                if (i == obstacleGrid.length - 1 && j == obstacleGrid[0].length - 1) {
                    dp[i][j] = 1;
                } else if (i == obstacleGrid.length - 1) {
                    dp[i][j] = dp[i][j + 1];
                } else if (j == obstacleGrid[0].length - 1) {
                    dp[i][j] = dp[i + 1][j];
                } else {
                    dp[i][j] = dp[i][j + 1] + dp[i + 1][j];
                }
            }
        }
        return dp[0][0];
    }
}

When execution: 1 ms, beat the 83.38% of all users to submit in Java
memory consumption: 37.7 MB, defeated 67.00% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2274

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104892386