Leetcode——63. Unique Paths II
题目原址
https://leetcode.com/problems/unique-paths-ii/description/
题目描述
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
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.
Note: m and n will be at most 100.
Example:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
解题思路
这个题的解题思路与Leetcode——64. Minimum Path Sum的解题思路一样,但是这里增加了障碍,在障碍部位不能进行通行。二维数组中元素的值为0或者1,为1表示为障碍。
- 因为机器人只能右走或者向下走,所以我们通过循环把二维数组中的障碍变为0,非障碍变为1
- 在第一行中,后面的元素值等于前面的元素值,为1表示可以同行;
- 在第一列中,下面的元素值等于上面的元素值,
- 除了第一行第一列的元素以外的元素的元素值 = 上面的元素 +左边的元素
- 最后返回最右边最下边的元素值
- 注意这里在第一行第一列的元素位置,其值等于1 - 本身的值,这样做主要是要考虑[[1]]这种情况是没有通路的
AC代码
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int row = obstacleGrid.length;
int line = obstacleGrid[0].length;
for(int i = 0; i < row; i++) {
for(int j = 0; j < line; j++) {
if(i == 0 && j == 0) {
obstacleGrid[i][j] = 1 - obstacleGrid[i][j];
continue;
}
if(obstacleGrid[i][j] == 1) obstacleGrid[i][j] = 0;
else if(i == 0) obstacleGrid[i][j] = obstacleGrid[i][j - 1];
else if(j == 0) obstacleGrid[i][j] = obstacleGrid[i - 1][j];
else
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
}
return obstacleGrid[row - 1][line - 1];
}
}
上一篇: 没学历、没背景 多次创业的他如今年入百亿
下一篇: Java从入门到精通_学习笔记05
推荐阅读
-
LeetCode 63. 不同路径 II
-
[leetcode]63. 不同路径 II
-
LeetCode——63.不同路径 II
-
63. Unique Paths II 动态规划
-
63. Unique Paths II 动态规划
-
【leetcode】Unique Paths II(动态规划)
-
LeetCode 63. Unique Paths II(动态规划)
-
[LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
-
【LeetCode62 Unique Paths】动态规划计算路径
-
【动态规划】LeetCode 63. Unique Paths II