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: Dynamic programming.
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 4 int res = 0; 5 int M = obstacleGrid.size(); 6 int N = obstacleGrid[0].size(); 7 int dp[M][N]; 8 dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1; 9 10 for(int i = 1; i < M; i++) { 11 dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i-1][0]; 12 } 13 for(int j = 1; j < N; j++) { 14 dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j-1]; 15 } 16 for(int i = 1; i < M; i++) { 17 for(int j = 1; j < N; j++) { 18 if(obstacleGrid[i][j] == 1) dp[i][j] = 0; 19 else { 20 dp[i][j] = dp[i-1][j] + dp[i][j-1]; 21 } 22 } 23 } 24 return dp[M-1][N-1]; 25 } 26 };