题目:
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.
解题:
类似于Unique Paths,简单DP,状态转移方程:f[i][j] = f[i - 1][j] + f[i][j]
只是注意0,1问题,1的话f[i][j] = 0
代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int row = obstacleGrid.size();
if(!row) return 0;
int col = obstacleGrid[0].size();
vector<vector<int> > f(row, vector<int>(col, 0));
f[0][0] = !obstacleGrid[0][0];
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(obstacleGrid[i][j]) {
f[i][j] = 0;
continue;
}
if(i) f[i][j] += f[i - 1][j];
if(j) f[i][j] += f[i][j - 1];
}
}
return f[row - 1][col - 1];
}
};