标签:
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.
解法:还是使用动态规划。不同的是若遇到障碍,则说明到此位置后面就行不通了,路径数目为0。注意初始化不能再是path[i][0]=1,path[0][j]=1(0<=i<m,0<=j<n),而是path[0][0]=1,因为第一行和第一列上就有可能有障碍。
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int res = 0; if(obstacleGrid.empty() || obstacleGrid[0].empty()) return res; int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<int> path(n, 0); path[0] = 1; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(obstacleGrid[i][j] == 1) path[j] = 0; else if(j > 0) path[j] += path[j - 1]; } } res = path[n - 1]; return res; } };
[LeetCode]20. Unique Paths II唯一路径
标签:
原文地址:http://www.cnblogs.com/aprilcheny/p/4865204.html