题目描述:
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为0,所以每次相加时只要把判断一下是否遇到障碍就可以了。还有就是要是起点或终点被障碍堵了,直接回0。
代码:
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { 4 int col = obstacleGrid[0].size(), row = obstacleGrid.size(); 5 if(obstacleGrid[0][0] == 1 || obstacleGrid[row-1][col-1] == 1) 6 return 0; 7 vector<int> ret(col+1, 0); 8 ret[1] = 1; 9 for(int i = 0; i < row; i++){ 10 for(int j = 0; j < col; j++){ 11 if(obstacleGrid[i][j] == 1) 12 ret[j+1] = 0; 13 else 14 ret[j+1] += ret[j]; 15 } 16 } 17 return ret[col]; 18 } 19 };