leetcode 63. Unique Paths II

来源:互联网 发布:淘宝店铺换身份证 编辑:程序博客网 时间:2024/06/05 06:03

题目

Follow up for “Unique Paths”:

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.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.

Note: m and n will be at most 100.

思路

跟62题思路差不多

代码

package leetcodeArray;import java.util.Arrays;public class Leetcode63UniquePaths2 {    public int uniquePathsWithObstacles(int[][] obstacleGrid) {        int m = obstacleGrid.length, n = obstacleGrid[0].length;        if(obstacleGrid[m-1][n - 1] == 1){            return 0;        }        Integer [][] path = new Integer[m][n];        Boolean flag = true;        for(int i = 0; i < m; ++i){            if(obstacleGrid[i][0] == 0 && flag)                path[i][0] = 1;            else{                path[i][0] = 0;                flag = false;            }        }        flag = true;        for(int i = 0; i < n; ++i){            if(obstacleGrid[0][i] == 0 && flag)                path[0][i] = 1;            else{                path[0][i] = 0;                flag = false;            }        }        for(int i  = 1; i < m; ++i){            for(int j = 1; j < n; ++j){                if(obstacleGrid[i - 1][j] ==1 && obstacleGrid[i][j - 1] == 0){                    path[i][j] = path[i][j - 1];                }                else if(obstacleGrid[i][j - 1] == 1 && obstacleGrid[i - 1][j] == 0){                    path[i][j] = path[i - 1][j];                }                else if(obstacleGrid[i][j - 1] == 0 && obstacleGrid[i - 1][j] == 0){                    path[i][j] = path[i - 1][j] + path[i][j - 1];                }                else{                    path[i][j] = 0;                }                System.out.println(path[i][j]);            }        }        return path[m - 1][n - 1];    }    public static void main(String[] args){        int[][] grib = {{1, 0}};        Leetcode63UniquePaths2 test = new Leetcode63UniquePaths2();        System.out.println(test.uniquePathsWithObstacles(grib));    }}

他山之玉

public int uniquePathsWithObstacles(int[][] obstacleGrid) {    int width = obstacleGrid[0].length;    int[] dp = new int[width];    dp[0] = 1;    for (int[] row : obstacleGrid) {        for (int j = 0; j < width; j++) {            if (row[j] == 1)                dp[j] = 0;            else if (j > 0)                dp[j] += dp[j - 1];        }    }    return dp[width - 1];}
原创粉丝点击