- 描述: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.
- 分析:这道题是在Leetcode problem 62. Unique Paths的基础上给区域中添加了障碍,以1代表障碍。
- 思路一:有了Unique Paths的经验,这道题直接选用动态规划解决。动态方程没有变化,只是在有障碍的地方将这个点的路径设为0。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int dis[m+1][n+1];
memset(dis, 0, sizeof(dis));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
if (obstacleGrid[i][j] == 0) dis[i + 1][j + 1] = 1;
} else {
if (obstacleGrid[i][j] == 0) dis[i + 1][j + 1] = dis[i + 1][j] + dis[i][j + 1];
}
}
}
return dis[m][n];
}
};