题目要求:
相比较于Unique Paths,多了一些限制,某些obstaclegrid=1的位置不能作为路径。
方法一样,采用动态规划,添加一些限制:
Method: flag[i][j] = obstacleGrid[i][j]==1? 0:flag[i-1][j]+flag[i][j-1];
class Solution {
public:
void non_uniqpath(vector<vector<int>>& obstacleGrid,int& num){
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> flag;
flag.resize(m);
for_each(flag.begin(),flag.end(),[n](vector<int>& pa){pa.resize(n,0);});
flag[0][0] = obstacleGrid[0][0]==1? 0:1;
for (int i=1;i<n;i++){
flag[0][i] = obstacleGrid[0][i]==1? 0:flag[0][i-1];
}
for (int i=1;i<m;i++){
flag[i][0] = obstacleGrid[i][0]==1? 0:flag[i-1][0];
}
for (int i=1;i<m;i++){
for (int j=1;j<n;++j){
flag[i][j] = obstacleGrid[i][j]==1? 0:flag[i-1][j]+flag[i][j-1];
}
}
num = flag[m-1][n-1];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int num=0;
non_uniqpath(obstacleGrid,num);
return num;
}
};