Unique Paths II

来源:互联网 发布:陕西广电网络悟空宽带 编辑:程序博客网 时间:2024/06/10 18:19

题目原型:

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.

基本思路:

和Unique Paths 类似,只是增加了障碍物的判断,具体思路是在原来的基础上判断如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0。

public int uniquePathsWithObstacles(int[][] obstacleGrid){if(obstacleGrid==null||obstacleGrid.length==0)return 0;int m = obstacleGrid.length;//数组行长int n = obstacleGrid[0].length;//数组列宽//若左上角第一个数为1和右下角最后一个数为1,表示走不通if(obstacleGrid[m-1][n-1]==1||obstacleGrid[0][0]==1)return 0;//初始化第一行和第一列,由于这两列的特殊化,只能从左到右或者从上到下走,所以一旦碰到障碍物则以下的都走不通了int startIndex = -1;for(int i = 0;i<m;i++){if(obstacleGrid[i][0]==1){obstacleGrid[i][0] = 0;startIndex = i;}else{if(startIndex==-1)obstacleGrid[i][0] = 1;elseobstacleGrid[i][0] = 0;}}startIndex = -1;//此处i从1开始for(int i = 1;i<n;i++){if(obstacleGrid[0][i]==1){obstacleGrid[0][i] = 0;startIndex = i;}else{if(startIndex==-1)obstacleGrid[0][i] = 1;elseobstacleGrid[0][i] = 0;}}//注意判断,如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0for(int i = 1;i<m;i++)for(int j = 1;j<n;j++){if(obstacleGrid[i][j]==1)obstacleGrid[i][j] = 0;elseobstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1];}return obstacleGrid[m-1][n-1];}



0 0