不同的路径 II .

 

不同的路径 II

 

"不同的路径" 的跟进问题:

现在考虑网格中有障碍物,那样将会有多少条不同的路径?

网格中的障碍和空位置分别用 1 和 0 来表示。

样例

如下所示在3x3的网格中有一个障碍物:

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

一共有2条不同的路径从左上角到右下角。

注意

m 和 n 均不超过100

只要在上一题的基础上检查一下对应位置是否有障碍物,若有障碍物则相应位置的路径数应为0.

注意第一行是若出现一个障碍物则这个位置和其右侧的所有位置的路径数都为0

 1 public class Solution {
 2     /**
 3      * @param obstacleGrid: A list of lists of integers
 4      * @return: An integer
 5      */
 6     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
 7         // write your code here
 8         int m = obstacleGrid.length;
 9         int n = obstacleGrid[0].length;
10         
11         int dp[] = new int[n];
12         int i;
13         for(i=0;i<n;i++) {
14             if(obstacleGrid[0][i]!=0)break;
15             dp[i] = 1;
16         }
17         for(i=i;i<n;i++) {
18             dp[i] = 0;
19         }
20         
21         for(int l=1;l<m;l++) {
22             if(obstacleGrid[l][0]!=0)dp[0]=0;
23             for(int j=1;j<n;j++) {
24                 if(obstacleGrid[l][j]==0)dp[j] += dp[j-1];
25                 else dp[j] = 0;
26             }
27         }
28         return dp[n-1];
29     }
30 }
View Code
原文地址:https://www.cnblogs.com/FJH1994/p/5019257.html