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.
题目标签:Array
题目给了我们一个matrix,里面1代表有障碍物,0代表空。这道题目和Unique Path 基本一样。之前我们是给start point 1的值,然后遍历matrix,拿left 和 top的值加起来。那么这题,1被用了,代表障碍物。那我们就用-1。首先来分析一下,如果起点或者终点都是1的话,那么就无路可走,直接return 0就可以。剩下的情况,对于每一个点,如果它是障碍物,就直接跳过;如果不是,那么拿left 和top 的加一起,那如果left 和 top 有障碍物的话,也跳过。最后把终点的值 * -1 就可以了。
当然,也可以另外新建一个matrix,过程是同样的方法,不同的是当这个点是1的话,就把这个点的值等于0。 这方法就需要多建一个matrix。
Java Solution:
Runtime beats 14.83%
完成日期:07/21/2017
关键词:Array
关键点:Dynamic Programming, 逆向思考
1 public class Solution 2 { 3 public int uniquePathsWithObstacles(int[][] obstacleGrid) 4 { 5 if(obstacleGrid[0][0] == 1 || 6 obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1] == 1) // obstacle at start point or finish point 7 return 0; 8 9 obstacleGrid[0][0] = -1; // start point 10 11 for(int i=0; i<obstacleGrid.length; i++) // row 12 { 13 for(int j=0; j<obstacleGrid[0].length; j++) // column 14 { 15 // if this is not obstacle 16 if(obstacleGrid[i][j] !=1) 17 { 18 // get left: left is not obstacle 19 if(j-1 >=0 && obstacleGrid[i][j-1] !=1) 20 obstacleGrid[i][j] += obstacleGrid[i][j-1]; 21 // get top: top is not obstacle 22 if(i-1 >=0 && obstacleGrid[i-1][j] !=1) 23 obstacleGrid[i][j] += obstacleGrid[i-1][j]; 24 } 25 26 } 27 } 28 29 return obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1] * -1; 30 } 31 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List