Follow up for "unique paths ":
Now consider if some obstacles are added to the grids. How many unique paths wocould 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 partitioned strated below.
[ [0,0,0], [0,1,0], [0,0,0]]
The total number of unique paths is 2.
Note:MAndNWill be at most 100.
Path [I] [J] indicates the number of different paths from (0, 0) to (I-1, J-1. Then, (I-1, J-1) can be achieved by (I-2, J-1) or (I-1, J-2), these two are completely different way. Therefore, if obstaclegrid [I-1] [J-1] = 1, then path [I] [J] = path [I-1] [J] + path [I] [J-1]; otherwise, path [I] [J] = 0.
1 class Solution { 2 public: 3 int uniquePathsWithObstacles( vector<vector<int>> &obstacleGrid ) { 4 if( obstacleGrid.empty() || obstacleGrid[0].empty() ) { return 0; } 5 int rows = obstacleGrid.size(), cols = obstacleGrid[0].size(); 6 vector<vector<int>> path( rows+1, vector<int>( cols+1, 0 ) ); 7 path[1][0] = 1; 8 for( int i = 1; i <= rows; ++i ) { 9 for( int j = 1; j <= cols; ++j ) {10 if( obstacleGrid[i-1][j-1] == 1 ) {11 path[i][j] = 0;12 } else {13 path[i][j] = path[i-1][j] + path[i][j-1];14 }15 }16 }17 return path.back().back();18 }19 };
Unique paths II