题目
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
.
在一个m*n的点阵中,从左上角到右下角,每次只能向下或者向右,并且有障碍物。求最多有几种走法?
1 承接上一题 http://blog.csdn.net/xift810/article/details/22218893,这道题目用dp来做,并且需要数组记录。
2 可以想到到每个点的走法总数,是它上面一个点和它左面一个点总数的和。
3 用一个相同的二维数组记录到相应的点的总数。其中当对应障碍的时候,为0。
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int row = obstacleGrid.length;
if(row==0){
return 0;
}
int col = obstacleGrid[0].length;
if(col==0){
return 0;
}
int[][] ways = new int[row][col];
boolean fuckingblock = false;
for(int i=0;i<row;i++){
if(fuckingblock||obstacleGrid[i][0]==1){
ways[i][0]=0;
fuckingblock=true;
continue;
}
ways[i][0]=1;
}
fuckingblock = false;
for(int j=0;j<col;j++){
if(fuckingblock||obstacleGrid[0][j]==1){
ways[0][j]=0;
fuckingblock=true;
continue;
}
ways[0][j]=1;
}
for(int i=1;i<row;i++){
for(int j=1;j<col;j++){
if(obstacleGrid[i][j]==1){
ways[i][j]=0;
continue;
}
ways[i][j]=ways[i][j-1]+ways[i-1][j];
}
}
return ways[row-1][col-1];
}