Sunday, January 4, 2015

Unique Paths II (LeetCode Array)

Question: 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.

Idea: Dynamic programming. The number of uniques paths from point (i,j) to (m-1, n-1) is path[i][j]= (obs[i][j]==1)? 0 : path[i+1][j]+path[i][j+1]. We can not go right (go down) from the last column (the last row). So the last column is path[i][n-1]=(obs[i][n-1]==1)? 0: path[i+1][n-1]. The same for last row.

Time: O(n^2) Space: O(n^2)

Code:
 public class Solution {  
   public int uniquePathsWithObstacles(int[][] obstacleGrid) {  
     if(obstacleGrid.length==0||obstacleGrid[0].length==0)  
       return 0;  
     int[][] obs=obstacleGrid;  
     int m=obs.length;  
     int n=obs[0].length;  
     int[][] path=new int[m][n];  
     path[m-1][n-1]=(obs[m-1][n-1]==1)?0:1;  
     for(int j=n-2;j>=0;j--)  
       path[m-1][j]=(obs[m-1][j]==1)?0:path[m-1][j+1];  
     for(int i=m-2;i>=0;i--)  
       path[i][n-1]=(obs[i][n-1]==1)?0:path[i+1][n-1];  
     for(int i=m-2;i>=0;i--)  
     {  
       for(int j=n-2;j>=0;j--)  
       {  
         path[i][j]=(obs[i][j]==1)?0:path[i+1][j]+path[i][j+1];  
       }  
     }  
     return path[0][0];  
   }  
 }  

No comments:

Post a Comment