63. Unique Paths II
来源:互联网 发布:淘宝网的技术模式分析 编辑:程序博客网 时间:2024/06/06 11:02
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.
题意:和Unique Paths 类似 只是多了个障碍的限制
思想:那么我们可以想办法把这题转化成 Unique Paths 来做
先判断第一列和第一行 如果位置为0 就把它标记为1 如果为1之后的位置全标记为0 因为都不可达
再来判断其它的位置,如果该位置是障碍为1时 就标记为0(能到达的路径为0) 如果为0时那么就按照Unique Paths的思想 标记为path[i-1][j]+path[i][j-1];
AC代码:时间O(n*m) 空间O(n*m)
class Solution {public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); //1代表该位置能到达的一条路径 0表示0条路径 ///判断第一列 如果该位置为0 就标记1 如果该位置为1 那么该位置以及后面位置全为0 int flagx = 1; for(int i =0;i<m;i++) if(obstacleGrid[i][0]==0&&flagx) obstacleGrid[i][0] = 1; else{ obstacleGrid[i][0] = 0; flagx=0; } ///判断第一行 如果该位置为0 就标记1 如果该位置为1 那么该位置以及后面位置全为0 int flagy = 1; obstacleGrid[0][0] ^=1; //obstacleGrid[0][0] 起始位置 取原始值 再判断这一行每一位置的路径数 for(int i =0;i<n;i++) if(obstacleGrid[0][i]==0&&flagy) obstacleGrid[0][i] = 1; else{ obstacleGrid[0][i] = 0; flagy=0; } //和Unique Paths的思想一样 这里遍历的位置为1代表有障碍 不可达 所以设置可达路径为0 for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(obstacleGrid[i][j]==0){ obstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1]; }else{ obstacleGrid[i][j] = 0; } } } return obstacleGrid[m-1][n-1]; }};
阅读全文
1 0
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 位移实现乘以2的倍数的乘法
- jwPlayer API
- 在Windows下基于VS2012配置openNI
- 使用RecyclerView实现的瀑布流高度自适应
- 带你玩转Visual Studio 系列 (转载)
- 63. Unique Paths II
- java常见问题整理
- Hibernate持久层框架详解
- Java 数组模拟队列
- Could not create connection to database server. Attempted reconnect 3 times. Giving up
- Android框架之路——Glide加载图片(结合RecyclerView、CardView)
- 应用程序调用_驱动B调用_驱动A_异步方法1_带完成历程_事件
- 如何定义一个只能在栈上生成对象的类
- Java的继承