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.
大致题意
在 unique paths I 基础上增加障碍物
题解
题目类型:动态规划
转移方程为:
path[i][j] = obstacleGrid[i][j] ? 0 : path[i - 1][j] + path[i][j - 1];
解如下
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> path(m, vector<int>(n, 1));
for (int i = 0; i < m; i++) {
for (int j = 0; j < obstacleGrid[i].size(); j++) {
if (obstacleGrid[i][j]) {
path[i][j] = 0;
} else if (i < 1 && j < 1) {
path[i][j] = !obstacleGrid[i][j];
} else if (i < 1) {
path[i][j] = path[i][j - 1];
} else if (j < 1) {
path[i][j] = path[i - 1][j];
} else {
path[i][j] = path[i - 1][j] + path[i][j - 1];
}
}
}
return path[m - 1][n - 1];
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。