码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Paths II

时间:2015-09-14 11:45:05      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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.

Example      

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     /**
 4      * @param obstacleGrid: A list of lists of integers
 5      * @return: An integer
 6      */ 
 7     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
 8         // write your code here
 9         
10         int row = obstacleGrid.size();
11         
12         if(row == 0)
13             return 0;
14             
15         int col = obstacleGrid[0].size();
16         
17         
18         vector<vector<int>> f(row, vector<int>(col,0));
19             
20         if(obstacleGrid[0][0] == 1)
21             return 0;
22             
23         f[0][0] = 1;
24         
25         for(int i = 0; i < row; ++i)
26         {
27             for(int j = 0; j < col; ++j)
28             {
29                 if(i == 0 && j == 0)
30                     continue;
31                     
32                 if(obstacleGrid[i][j] == 1)
33                 {
34                     f[i][j] = 0;
35                     continue;
36                 }
37                 
38                 if(i == 0)
39                     f[i][j] = f[i][j-1];
40                 else if(j == 0)
41                     f[i][j] = f[i-1][j];
42                 else
43                     f[i][j] = f[i-1][j] + f[i][j-1];
44             }
45         }
46         
47         return f[row-1][col-1];
48     }
49 };

 

Unique Paths II

标签:

原文地址:http://www.cnblogs.com/cis2000/p/4806548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!