Follow up for "unique paths ":
Now consider if some obstacles are added to the grids. How many unique paths wocould there be?
An obstacle and empty space is marked1And0Respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as partitioned strated below.
[ [0,0,0], [0,1,0], [0,0,0]]
The total number of unique paths is2.
Note: MAndNWill be at most 100.
Question: http://www.cnblogs.com/sunshineatnoon/p/4108167.htmlis very difficult. It takes two points:
- Where there are obstacles, the number of methods that can be reached is 0;
- When initializing the result matrix, if there is an obstacle at a certain position in the first row (column), all the elements after this row (column) element are 0 and cannot be set to 1; for example, if an obstacle matrix [, 0] is specified, the initialized matrix should be [, 0] instead of [, 1], because there is an obstacle, the Matrix cannot be reached at any position.
The Code is as follows:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 int m = obstacleGrid.length; 4 int n = obstacleGrid[0].length; 5 if(m==0 && n == 0) 6 return 0; 7 8 int[][] PathNum = new int[m][n]; 9 for(int i = 0;i < m;i++)10 if(obstacleGrid[i][0] != 1)11 PathNum[i][0] = 1;12 else 13 break;14 for(int i = 0;i < n;i++)15 if(obstacleGrid[0][i] != 1)16 PathNum[0][i] = 1;17 else18 break;19 20 for(int i = 1;i < m;i++)21 for(int j = 1;j < n;j++){22 if(obstacleGrid[i][j] != 1)23 PathNum[i][j] = PathNum[i-1][j]+PathNum[i][j-1]; 24 }25 26 return PathNum[m-1][n-1];27 }28 }