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

Unique Paths II

时间:2014-08-12 16:40:14      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   strong   for   ar   

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.

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

动态规划,时间复杂度O(m*n), 空间复杂度O(m*n)。

Unique Paths II,布布扣,bubuko.com

Unique Paths II

标签:style   blog   color   os   io   strong   for   ar   

原文地址:http://www.cnblogs.com/Kai-Xing/p/3907236.html

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