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.

[
  [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.

这道题是在unique path的基础上加上了障碍物,解决办法还是动态规划,代码如下:

 1 public class Solution {
 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
 3         int m = obstacleGrid.length;
 4         int n = obstacleGrid[0].length;
 5         int[][] dp = new int[m][n];
 6         
 7         dp[m-1][n-1] = obstacleGrid[m-1][n-1]==1?0:1;
 8         for(int i=m-2;i>=0;i--){
 9             if(obstacleGrid[i][n-1]==1){
10                 dp[i][n-1]=0;
11             }else{
12                 dp[i][n-1] =dp[i+1][n-1];
13             }
14         }
15         for(int i=n-2;i>=0;i--){
16             if(obstacleGrid[m-1][i]==1){
17                 dp[m-1][i] = 0;
18             }else{
19                 dp[m-1][i] = dp[m-1][i+1];
20             }
21         }
22         for(int i=m-2;i>=0;i--){
23             for(int j=n-2;j>=0;j--){
24                 if(obstacleGrid[i][j]==1){
25                     dp[i][j] =0;
26                 }else{
27                     
28                     dp[i][j] = dp[i][j+1]+dp[i+1][j];
29                     
30                 }
31             }
32         }
33         return dp[0][0];
34     }
35 }

看了discussion后,发现大神的解法很简洁,用的办法我取名字为光的直线传播,代码如下:

 1 public class Solution {
 2     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
 3         int n = obstacleGrid[0].length;
 4         int[] dp = new int[n];
 5         dp[0] = 1;
 6         for(int i=0;i<obstacleGrid.length;i++){
 7             for(int j=0;j<obstacleGrid[i].length;j++){
 8                 if(obstacleGrid[i][j]==1){
 9                     dp[j] = 0;
10                 }else if(j>0){
11                     dp[j]+=dp[j-1];
12                 }
13             }
14         }
15         return dp[n-1];
16     }
17 }

这个解法也是用的dp方法解决的,只不过顺序是相反的,答案也是相反的,相当于镜面映射了。

posted @ 2017-02-10 11:44  CodesKiller  阅读(129)  评论(0编辑  收藏  举报