63. Unique Paths II
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.
1 | [ |
The total number of unique paths is 2
.
Note: m and n will be at most 100.
题意:
62. Unique Paths变形,现在考虑在网格中添加一些障碍物。会有多少独特的路径?
在方格中,障碍物和空区分别标有‘1’和‘0’。
思路:
思路同62. Unique Paths](http://blog.taoaili999.cn/2017/07/27/63-Unique-Paths-II/),都是利用动态规划,不同点是要考虑出现障碍物,把有障碍物(obstacles)的地方的路径数直接设置为0,特别注意数据类型界限问题,越界会获取不到正确的数据而造成未知错误。根据障碍物出现的位置,设置辅助矩阵元素值为零主要分三种情况:
1)在矩阵第一个元素,即obstacleGrid[0][0],这样不能到达,所以直接返回路径数为0。
2)在矩阵第一行的某个元素,即obstacleGrid[0][j],这样第一行j列之后不能到达,第一行j列之后辅助矩阵元素直接设0。
3)在矩阵第一列的某个元素,即obstacleGrid[i][0],这样第一列i行之后不能到达,第一列i行之后辅助矩阵元素直接设0。
4)在矩阵中某个元素,即obstacleGrid[i][j](i > 0,j > 0),辅助矩阵元素直接设0。
1 | class Solution { |
Java Code
1 | class Solution { |