Follow up for "Unique Paths":
Now consider if some obstacles is added to the grids. How many unique paths would there be?
An obstacle and empty space are marked as and respectively in the 1 0 grid.
Note
m and N would be is at most 100.
Example
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 .
Analysis:
DP:D[I][J] = D[i][j-1]+d[i-1][j].
Note:we can use 1D array to perform the DP. Since D[i][j] depends on d[i][j-1], i.e., the new d[][j-1], we should increase J from 0 to end. If D[i][j] depends on d[i-1][j-1] and we should decrease J from end to 0.
Solution:
1 Public classSolution {2 /**3 * @paramobstaclegrid:a List of lists of integers4 * @return: An integer5 */6 Public intUniquepathswithobstacles (int[] obstaclegrid) {7 intRowNum =obstaclegrid.length;8 if(rownum==0)return0;9 intColnum = obstaclegrid[0].length;Ten if(colnum==0)return0; One if(obstaclegrid[0][0]==1)return0; A - int[] Path =New int[Colnum]; -Path[0] =1; the for(inti=1;i<colnum;i++) - if(obstaclegrid[0][i]==1) path[i]=0; - ElsePath[i] = path[i-1]; - + for(inti=1;i<rownum;i++){ - if(obstaclegrid[i][0]==1) path[0]=0; + for(intj=1;j<colnum;j++) A if(obstaclegrid[i][j]==1) path[j]=0; at Elsepath[j]=path[j-1]+Path[j]; - - } - - - returnPath[colnum-1]; in } -}
Lintcode-unique Path II