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     vector<vector<int> >result;
 2     int search(int sx, int sy, int ex, int ey, vector<vector<int> > &obstacleGrid){
 3         if(sx > ex || sy > ey || obstacleGrid[sx][sy] == 1)
 4             return 0;
 5         if(result[sx][sy] != -1)
 6             return result[sx][sy];
 7         if(sx == ex && sy == ey)
 8             return 1;
 9         result[sx][sy] = search(sx+1, sy, ex, ey, obstacleGrid) + search(sx, sy+1, ex, ey, obstacleGrid);
10         return result[sx][sy];
11     }
12     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
13         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         result.clear();
16         int m = obstacleGrid.size();
17         if(m == 0)
18             return 0;
19         int n = obstacleGrid[0].size();
20         if(n == 0)
21             return 0;
22         int i,j;
23         for(i = 0; i < m; i++){
24             vector<int> tmp(n, -1);
25             result.push_back(tmp);
26         }
27         return search(0, 0, m-1, n-1, obstacleGrid);
28     }

 

posted on 2013-11-08 20:48  waruzhi  阅读(139)  评论(0编辑  收藏  举报

导航