LeetCode OJ 之 Unique Paths II(不同路径 - 二)
2014-12-14 16:44
267 查看
题目:
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
1and
0respectively
in the grid.
不同路径一参看:http://blog.csdn.net/u012243115/article/details/41925421.
现在考虑如果网格中有某些障碍,那么有多少种不同的路径?
障碍和空格在格子中分别被标记为 1 和 0 ,即遇到 0 可以通过,遇到 1 不能通过。
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.
思路:
1、动态规划法,相比于没有障碍时,在初始化第一行和第一列以及使用状态转移方程的条件时变化了。class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)
{
int m = obstacleGrid.size();//行数
if(m < 1)
return 0;
int n = obstacleGrid[0].size();//列数
vector<vector<int> > f (m , vector<int>(n , 0));//m x n 的数组
if(m < 1 || n < 1)
return 0;
//如果第一个有障碍,则没有路径
if(obstacleGrid[0][0] == 1)
return 0;
//初始化第一行,如果遇到有障碍,则它之后的都要初始化为0,之后的路都不通了
for(int i = 0 ; i < n ; i++)
{
if(obstacleGrid[0][i] == 0)
f[0][i] = 1;
else
{
for(int j = i ; j < n ; j++)
{
f[0][j] = 0;
}
break;
}
}
//初始化同第一行初始化
for(int i = 0 ; i < m ; i++)
{
if(obstacleGrid[i][0] == 0)
f[i][0] = 1;
else
{
for(int j = i ; j < m ; j++)
{
f[j][0] = 0;
}
break;
}
}
for(int i = 1 ; i < m ; i++)
{
for(int j = 1 ; j < n ; j++)
{
//如果有障碍,则当前路径数为0
if(obstacleGrid[i][j] == 1)
f[i][j] = 0;
else
f[i][j] = f[i-1][j] + f[i][j-1];
}
}
return f[m-1][n-1];
}
};
2、优化动态规划时的空间复杂度
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)
{
int m = obstacleGrid.size();//行数
if(m < 1)
return 0;
int n = obstacleGrid[0].size();//列数
//如果第一个或者最后一个有障碍,则没有路径
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
return 0;
vector<int> f(n , 0);
f[0] = 1; //此时obstacleGrid[0][0]不为1
//把第一行和第一列的计算也放在for循环里,
//对于第一行,如果当前有障碍,则f一定为0,如果当前没有障碍,则和前一个f保持一致
//对于第一列,如果当前有障碍,则f一定为0,如果当前没有障碍,则和前一行的f[0]保持一致
for(int i = 0 ; i < m ; i++)
{
for(int j = 0 ; j < n ; j++)
{
if(obstacleGrid[i][j] == 1 )
f[j] = 0;
else
if(j != 0)
f[j] = f[j] + f[j-1];
//else
// f[j] = f[j]; //即如果j=0,即j为第一列,则f[j] 和上一行的f[j]保持不变
}
}
return f[n-1];
}
};
相关文章推荐
- lintcode unique-paths-ii 不同的路径ii
- [LeetCode] Unique Paths II 不同的路径之二
- LeetCode题库解答与分析——#63.不同路径IIUniquePathsII
- LeetCode OJ:Unique Paths II(唯一路径II)
- LintCode UniquePathsII 不同的路径II
- Leet Code 63 Unique Paths II - 不同路径 - Java
- LeetCode OJ 之 Unique Binary Search Trees II (不同的二叉搜索树 - 二)
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- [Leetcode] unique paths ii 独特路径
- LeetCode OJ 系列之63 Unique Paths II --Python
- LintCode UniquePaths 不同的路径
- [LeetCode]20. Unique Paths II唯一路径
- Unique Paths II:统计路径
- Unique Paths和Unique Paths II 路径
- LeetCode OJ:Unique Paths(唯一路径)
- LeetCode | Unique Paths II(唯一路径II)
- LeetCode OJ:Unique Paths II
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- LeetCode OJ--Unique Paths II **
- LeetCode OJ - Unique Paths II