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.
Solution: The same to Unique Paths, just add obstacle check.
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 4 if(obstacleGrid.size() <= 0 || obstacleGrid[0].size() <= 0) 5 return 0; 6 7 int row = obstacleGrid.size(); 8 int column = obstacleGrid[0].size(); 9 vector<int> path_nums(column, 0); 10 for(int i = 0; i < row; i ++) { 11 int row_idx = row - 1 - i; 12 for(int j = 0; j < column; j ++ ) { 13 int column_idx = column - 1 - j; 14 if(i == 0 && j == 0 && obstacleGrid[row_idx][column_idx] == 1) 15 return 0; 16 if(i == 0 && j == 0 && obstacleGrid[row_idx][column_idx] == 0) { 17 path_nums[j] = 1; 18 }else { 19 if(obstacleGrid[row_idx][column_idx] == 1) { 20 path_nums[j] = 0; 21 }else { 22 if(j != 0) 23 path_nums[j] += path_nums[j - 1]; 24 } 25 } 26 } 27 } 28 return path_nums[column - 1]; 29 } 30 };