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.

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)。

posted on 2014-08-12 14:30  Ryan-Xing  阅读(104)  评论(0编辑  收藏  举报