您的位置:首页 > 产品设计 > UI/UE

Unique Paths II

2014-03-28 09:27 176 查看
题目原型:

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;
else
obstacleGrid[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;
else
obstacleGrid[0][i] = 0;
}
}
//注意判断,如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0
for(int i = 1;i<m;i++)
for(int j = 1;j<n;j++)
{
if(obstacleGrid[i][j]==1)
obstacleGrid[i][j] = 0;
else
obstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1];
}
return obstacleGrid[m-1][n-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: