63. Unique Paths II

Posted 三颗心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了63. Unique Paths II相关的知识,希望对你有一定的参考价值。

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.

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
 4         if(obstacleGrid.empty() || obstacleGrid[0].empty()){
 5             return 0;
 6         }
 7         int row = obstacleGrid.size();
 8         int col = obstacleGrid[0].size();
 9         
10         int dp[row][col];
11         
12         dp[0][0] = (obstacleGrid[0][0] == 0 ? 1 : 0);
13         
14         for(int i = 1; i < row; i++){
15             dp[i][0] = ((dp[i-1][0] == 1 && obstacleGrid[i][0] == 0)? 1 : 0);
16         }
17         
18         for(int j = 1; j < col; j++){
19             dp[0][j] = ((dp[0][j-1] == 1 && obstacleGrid[0][j] == 0)? 1: 0);
20         }
21         
22         for(int i = 1 ; i < row; i++){
23             for(int j = 1 ; j < col;j++){
24                 if(obstacleGrid[i][j] == 1){
25                     dp[i][j] = 0;
26                 }else{
27                     dp[i][j] = dp[i-1][j]+dp[i][j-1];
28                 }
29             }
30         }
31         
32         return dp[row-1][col-1];
33     }
34 };

 

以上是关于63. Unique Paths II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode: 63. Unique Paths II(Medium)

63. Unique Paths II

63. Unique Paths II

java 63. Unique Paths II(#)。java

java 63. Unique Paths II(#)。java

java 63. Unique Paths II(#)。java