LeetCode——unique-paths

Q: a robot (starting position, the figure labeled "start") is the size of m × n in the upper left corner of the map.
Each time the robot moves to the right or down. Robots are to reach the bottom right corner of the map. (End position, the figure labeled "Finish" a).
How many different kinds can come to the end of the path from the starting point?
Notes: m and n is less than or equal to 100

A: A typical dynamic programming problem.

    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i ++)
            dp[i][0] = 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];
    }

Q: continue to think about the title "Unique Paths":
If you add a number of obstacles in the figure, how many different paths?
Respectively 0 and represents empty areas and disorders
, for example,
the figure shows a central obstacle in FIG. 3 a * 3.
[↵ [0,0,0], ↵ [ 0,1,0], ↵ [0,0,0] ↵]
There are two different paths
Remark: m and n does not exceed 100.
A: where there is an obstacle like set to 0

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
        for (int i = 0; i < dp.length; i ++ ) {
            if(obstacleGrid[i][0] == 1) break;
            dp[i][0] = 1;
        }
        for (int i = 0; i < dp[0].length; i ++ ) {
            if(obstacleGrid[0][i] == 1) break;
            dp[0][i] = 1;
        }
        for (int i = 1; i < dp.length; i ++ ) {
            for (int j = 1; j < dp[0].length; j ++ ) {
                if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
                else dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }

Guess you like

Origin www.cnblogs.com/xym4869/p/12527512.html