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.
DP 有障碍的迷宫
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int f[m][n],i,j;
f[0][0] = obstacleGrid[0][0]==1?0:1;
for(i=1;i<m;i++){
f[i][0] = obstacleGrid[i][0]==1?0:f[i-1][0];
}
for(j=1;j<n;j++){
f[0][j] = obstacleGrid[0][j]==1?0:f[0][j-1];
}
for(i=1;i<m;i++){
for(j=1;j<n;j++){
f[i][j] = obstacleGrid[i][j]==1?0:f[i-1][j]+f[i][j-1];
}
}
return f[m-1][n-1];
}
};