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

Unique Paths II

时间:2014-08-25 20:55:04      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   cti   

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.

思路:path[i][j]表示从(0,0)到达(i-1,j-1)的不同路径数。则,(i-1,j-1)可以由(i-2,j-1)或者(i-1,j-2)达到,这两种是完全不同的走法。因此,若obstacleGrid[i-1][j-1] == 1,则path[i][j] = path[i-1][j] + path[i][j-1];否则,path[i][j] = 0。

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

 

Unique Paths II

标签:style   blog   color   os   io   for   ar   div   cti   

原文地址:http://www.cnblogs.com/moderate-fish/p/3935605.html

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