标签:style blog http color io for ar cti
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
1and0respectively 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] ]
算法思路:
跟[leetcode]Unique Paths几乎一样,就加上一个判断好了。
代码如下:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if(obstacleGrid == null || obstacleGrid.length == 0) return 0; 4 int height = obstacleGrid.length; 5 int width = obstacleGrid[0].length; 6 int[][] dp = new int[height][width]; 7 for(int i = 0; i < width;i++){ 8 if(obstacleGrid[0][i] == 0){ 9 dp[0][i] = 1; 10 }else{ 11 break; 12 } 13 } 14 for(int i = 0; i < height;i++){ 15 if(obstacleGrid[i][0] == 0){ 16 dp[i][0] = 1; 17 }else{ 18 break; 19 } 20 } 21 for(int i = 1; i < height; i++){ 22 for(int j = 1; j < width;j++){ 23 if(obstacleGrid[i][j] == 0) 24 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 25 } 26 } 27 return dp[height - 1][width - 1]; 28 } 29 }
[leetcode]Unique Paths II,布布扣,bubuko.com
标签:style blog http color io for ar cti
原文地址:http://www.cnblogs.com/huntfor/p/3900291.html