Unique Paths II_Week19
题目说明:
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.
难度: Medium
解题思路:
题意:
本题的初始版如下:
题目:(Unique Paths ) ←链接戳这里
给定一个图(即m*n的方格),从最左上角的(0,0)出发,到达右下角的(m-1,n-1)格子,行进方向只能往右或者往下移动,问有几条不同的路径。
这道题可以从结束状态反推,即站在格子(m-1,n-1)上,上一步只可能是从左边来的,或者从右边来的;回退到左边的格子上,也只可能是从该格的左边或者上方来的。
这样就可以推出这样的动态方程:
P[i][j] = P[i][j-1]+P[i-1][j]
因为格子至少有一个,则至少有一条路,将表格初始化全为1,而从(1,1)开始遍历,使用上方的转移方程就可得出解为最终的P[m-1][n-1].
而本题则是上面描述的题的进阶版,即多了障碍物。其实跟第一版问题没有太大的差别,差别只在于遍历的同时检查该点是否有障碍,若有障碍则表示不可达,则设置P[i][j]=0,则最终结果也是P[m-1][n-1]。
代码如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int m = obstacleGrid.size() , n = obstacleGrid[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
dp[0][1] = 1;
for(int i = 1 ; i <= m ; ++i)
for(int j = 1 ; j <= n ; ++j)
if(!obstacleGrid[i-1][j-1]) //若该点有障碍物,则不可达,则设置值为0 (因初始化为0所以不用另外再设置)
dp[i][j] = dp[i-1][j]+dp[i][j-1];
return dp[m][n];
}
};