[Leetcode]-Unique Paths II
来源:互联网 发布:二维平移变换矩阵 编辑:程序博客网 时间:2024/05/14 18:26
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.
Hide Tags Array Dynamic Programming
Hide Similar Problems (M) Unique Paths
题目:这道题目和Unique Paths类似,只不过在其中增加了障碍物,obstacleGrid[i][j]中为0表示无障碍,obstacleGrid[i][j]为1表示为障碍物不能从这里通过。
思路:
分配path[obstacleGridRowSize][obstacleGridColSize]二维数组,用来存放能到当前位置的路径数目
1、设置首行,只要已发现出现obstacleGrid[0][i]第一个有1,则将后面的path[0][j]全部设置为0;
2、设置首列,只要已发现出现obstacleGrid[i][0]第一个有1,则将后面的path[j][0]全部设置为0;
3、循环其他所有位置:
1、当发现 obstacleGrid[i][j]为1,说明此路不通,对应的path[i][j]设置为0
2、否则就计算path[i][j] = path[i-1][j] + path[i][j-1];
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize) { int m = obstacleGridRowSize; int n = obstacleGridColSize; int** path =(int**)malloc(sizeof(int*) * m); for(int i=0;i<m;i++) path[i] = (int*)malloc(sizeof(int)*n); for(int i=0;i<m;i++) { if(1 == obstacleGrid[i][0]) { for(int j=i;j<m;j++) path[j][0] = 0; break; } else path[i][0] = 1; } for(int i=0;i<n;i++) { if(1 == obstacleGrid[0][i]) { for(int j=i;j<n;j++) path[0][j] = 0; break; } else path[0][i] = 1; } for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { if(1 == obstacleGrid[i][j]) path[i][j] = 0; else path[i][j] = path[i-1][j] + path[i][j-1]; } } int r = path[m-1][n-1]; for(int i=0;i<m;i++) free(path[i]); free(path); return r;}
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths II
- [LeetCode] Unique Paths II
- [LeetCode]Unique Paths II
- [leetcode]Unique Paths II
- LeetCode-Unique Paths II
- [leetcode] Unique Paths II
- LeetCode - Unique Paths II
- LeetCode:Unique Paths II
- 【LeetCode】Unique Paths II
- leetcode Unique Paths II
- LeetCode Unique Paths II
- LeetCode | Unique Paths II
- Leetcode: Unique Paths II
- LeetCode Unique Paths II
- Unique Paths II -- LeetCode
- [LeetCode] Unique Paths II
- 进制转换
- 【MySQL】(4)操作数据表中的记录
- 编码 UTF-8 的不可映射字符http://www.cnblogs.com/zz0412/p/jenkins02.html
- postgres修改使用密码登录的方法
- (八十一)利用系统自带App来实现导航
- [Leetcode]-Unique Paths II
- 最短路径算法
- 南阳oj NYOJ 贪心 找点 题目891
- c语言归并排序(poj2299)《学习记录》
- 开门人和关门人
- 将Oracle数据库表导入到SQL Server中
- 1、文件ZIp的对byte[]的压缩和解压缩
- 2015 Multi-University Training Contest 1 Annoying problem
- uva11806(数论)