这题和#62相仿,应该注意的是如果在应该初始化的边上有被block,那么block之后的点到终点的path数应该初始化为“0”。以及如果有一点的右方和下方均被block,那么改点也是没有到终点的路径的,应初始化为“0”
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0;
// else if(obstacleGrid.length == 1 || obstacleGrid[0].length == 1) return 1;
int table[][] = new int[obstacleGrid.length][obstacleGrid[0].length];
boolean obstacleFlag = false;
for(int i = 0; i < obstacleGrid.length; i++) {
if(obstacleGrid[i][0]==1) obstacleFlag = true;
if(obstacleFlag == true) table[i][0] = 0;
else if(obstacleFlag == false) table[i][0] = 1;
}
obstacleFlag = false;
for(int i = 0; i < obstacleGrid[0].length; i++) {
if(obstacleGrid[0][i]==1) obstacleFlag = true;
if(obstacleFlag == true) table[0][i] = 0;
else if(obstacleFlag == false) table[0][i] = 1;
}
for(int i = 1; i < obstacleGrid.length; i++) {
for(int j = 1; j < obstacleGrid[0].length; j++) {
if(obstacleGrid[i][j] == 1) table[i][j]=0;
else if(obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] == 1) table[i][j]=0;
else table[i][j] = table[i-1][j] + table[i][j-1];
}
}
return table[obstacleGrid.length-1][obstacleGrid[0].length-1];
}
}
Fight On!