[Leetcode] 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 as1and0respectively 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 is2.

Note: m and n will be at most 100.

 题意:增加障碍,不能到达障碍,不能越过障碍。

思路:思路和unique paths是一样的,只是要判断当前值是否为1,若是,则其对应的dp数组中赋值为0,不是时,状态方程是:dp[i][j]=dp[i-1][j]+dp[i][j-1]。代码如下:

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) 
 4     {
 5         int m=obstacleGrid.size(),n=obstacleGrid[0].size();
 6         vector<vector<int>> dp(m,vector<int>(n,0));
 7         if(m==0||n==0)  return 1;
 8         if(obstacleGrid[0][0]==1) return 0;
 9         dp[0][0]=1;     10         //初始行
11         for(int i=1;i<m;++i)
12         {
13             if(obstacleGrid[i][0] ==1)
14             {
15                break;
16             }
17             else
18                 dp[i][0]=1;
19         }
20         //初始列
21         for(int i=1;i<n;++i)
22         {
23             if(obstacleGrid[0][i] ==1)
24             {
25                 break;
26             }
27             else
28                 dp[0][i]=1;
29         }
30 
31         for(int i=1;i<m;++i)
32         {
33             for(int j=1;j<n;++j)
34             {
35                 if(obstacleGrid[i][j] !=1)
36                     dp[i][j]=dp[i-1][j]+dp[i][j-1];
37             }
38         }
39 
40         return dp[m-1][n-1];
41     }
42 };

 

 当用一维数组去简化时,要注意些问题,仅一行,或者仅一列时,还要依次的确定数组dp[]中对应的值,不是像上一题那样简单赋值为1就行,所以,遍历时,行和列的起始点都是从0开始;另外也得注意的是,数组dp中的当前的前一个是否存在,即, j >0。代码如下:

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) 
 4     {
 5         int row=obstacleGrid.size(),col=obstacleGrid[0].size();
 6         if(obstacleGrid[0][0]==1)   return 0;
 7         vector<int> dp(col,0);
 8         dp[0]=1;
 9 
10         for(int i=0;i<row;++i)
11         {
12             for(int j=0;j<col;++j)
13             {
14                 if(obstacleGrid[i][j]==1)
15                     dp[j]=0;
16                 else if(j>0)
17                     dp[j]+=dp[j-1];
18             }
19         }
20         return dp[col-1];    
21     }
22 };

 

posted @ 2017-07-05 15:46  王大咩的图书馆  阅读(221)  评论(0编辑  收藏  举报