|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +importutils.CommonUtils; |
| 4 | + |
| 5 | +/**63. Unique Paths II QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 72924 |
| 7 | +Total Submissions: 243328 |
| 8 | +Difficulty: Medium |
| 9 | +Follow up for "Unique Paths": |
| 10 | +
|
| 11 | +Now consider if some obstacles are added to the grids. How many unique paths would there be? |
| 12 | +
|
| 13 | +An obstacle and empty space is marked as 1 and 0 respectively in the grid. |
| 14 | +
|
| 15 | +For example, |
| 16 | +There is one obstacle in the middle of a 3x3 grid as illustrated below. |
| 17 | +
|
| 18 | +[ |
| 19 | + [0,0,0], |
| 20 | + [0,1,0], |
| 21 | + [0,0,0] |
| 22 | +] |
| 23 | +The total number of unique paths is 2. |
| 24 | +
|
| 25 | +Note: m and n will be at most 100.*/ |
| 26 | +publicclassUniquePathsII { |
| 27 | +/**Idea: grid[i][j] has to be set to zero if obstacleGrid[i][j] == 1, |
| 28 | + * otherwise, we can get dp[i][j] from its top and left dp.*/ |
| 29 | +publicintuniquePathsWithObstacles(int[][]obstacleGrid) { |
| 30 | +if(obstacleGrid ==null ||obstacleGrid.length ==0)return0; |
| 31 | + |
| 32 | +intheight =obstacleGrid.length,width =obstacleGrid[0].length; |
| 33 | +int[][]dp =newint[height][width]; |
| 34 | +dp[0][0] =obstacleGrid[0][0] ==1 ?0 :1; |
| 35 | +for(inti =1;i <height;i++){ |
| 36 | +dp[i][0] =obstacleGrid[i][0] ==1 ?0 :dp[i-1][0]; |
| 37 | + } |
| 38 | +for(intj =1;j <width;j++){ |
| 39 | +dp[0][j] =obstacleGrid[0][j] ==1 ?0 :dp[0][j-1]; |
| 40 | + } |
| 41 | + |
| 42 | +for(inti =1;i <height;i++){ |
| 43 | +for(intj =1;j <width;j++){ |
| 44 | +if(obstacleGrid[i][j] ==1)dp[i][j] =0; |
| 45 | +else { |
| 46 | +intpaths =0; |
| 47 | +if(obstacleGrid[i-1][j] ==0)paths +=dp[i-1][j]; |
| 48 | +if(obstacleGrid[i][j-1] ==0)paths +=dp[i][j-1]; |
| 49 | +dp[i][j] =paths; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +CommonUtils.printMatrix(dp); |
| 54 | +returndp[height-1][width-1]; |
| 55 | + } |
| 56 | + |
| 57 | +publicstaticvoidmain(String...strings){ |
| 58 | +UniquePathsIItest =newUniquePathsII(); |
| 59 | +// int[][] obstacleGrid = new int[3][3]; |
| 60 | +// obstacleGrid[0][0] = 0; |
| 61 | +// obstacleGrid[0][1] = 0; |
| 62 | +// obstacleGrid[0][2] = 0; |
| 63 | +// obstacleGrid[1][0] = 0; |
| 64 | +// obstacleGrid[1][1] = 1; |
| 65 | +// obstacleGrid[1][2] = 0; |
| 66 | +// obstacleGrid[2][0] = 0; |
| 67 | +// obstacleGrid[2][1] = 0; |
| 68 | +// obstacleGrid[2][2] = 0; |
| 69 | + |
| 70 | +// int[][] obstacleGrid = new int[1][2]; |
| 71 | +// obstacleGrid[0][0] = 1; |
| 72 | +// obstacleGrid[0][1] = 0; |
| 73 | + |
| 74 | +int[][]obstacleGrid =newint[2][2]; |
| 75 | +obstacleGrid[0][0] =0; |
| 76 | +obstacleGrid[0][1] =0; |
| 77 | +obstacleGrid[1][0] =0; |
| 78 | +obstacleGrid[1][1] =1; |
| 79 | + |
| 80 | +CommonUtils.printMatrix(obstacleGrid); |
| 81 | +System.out.println(test.uniquePathsWithObstacles(obstacleGrid)); |
| 82 | + } |
| 83 | + |
| 84 | +} |