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