题目:
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.
解法一:我的解法
1 public int uniquePathsWithObstacles(int[][] obstacleGrid) 2 { 3 int m=obstacleGrid.length; 4 //if(m==0) return 1; 5 int n=obstacleGrid[0].length; 6 int [][] grids = new int [m+1][n+1]; 7 grids[m][n-1]=1; 8 for(int i=m-1;i>=0;i--) 9 { 10 for (int j=n-1;j>=0;j--) 11 { 12 grids[i][j]=(obstacleGrid[i][j]==1) ? 0:grids[i+1][j]+grids[i][j+1]; 13 } 14 } 15 16 return grids[0][0]; 17 18 }
解法二:九章算法的解法
1 public int uniquePathsWithObstacles(int[][] obstacleGrid) 2 { 3 int m=obstacleGrid.length; 4 //if(m==0) return 1; 5 int n=obstacleGrid[0].length; 6 int [][] grids = new int [m][n]; 7 for (int i = 0; i < m; i++) 8 { 9 if (obstacleGrid[i][0] != 1) { 10 grids[i][0] = 1; 11 } else { 12 //grids[i][0] = 0; 13 break; //第一列!错过了就不会再回到第一列!只能往右边和下边走。 14 } 15 } 16 17 for (int i = 0; i < n; i++) { 18 if (obstacleGrid[0][i] != 1) { 19 grids[0][i] = 1; 20 } else { 21 //grids[0][i] = 0; 22 break; //第一行!错过了就不会回到第一行。 23 } 24 } 25 26 27 28 for(int i=1;i<m;i++) 29 { 30 for (int j=1;j<n;j++) 31 { 32 grids[i][j]=(obstacleGrid[i][j]==1) ? 0:grids[i-1][j]+grids[i][j-1]; 33 } 34 } 35 36 return grids[m-1][n-1]; 37 38 }