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

LeetCode OJ:Unique Paths II(唯一路径II)

2015-10-22 16:37 411 查看
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]
]

这个与前面那个题目基本上差不多,具体就是多了障碍,实际上遇到障碍的话把到该点的路径的数目置为0就可以了,其他的基本上与前面相同:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0) return 0;
vector<vector<int>> res(obstacleGrid.size(), vector<int>(obstacleGrid[0].size(), 0));
int maxHor = obstacleGrid.size();
int maxVer = obstacleGrid[0].size();
res[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
for(int i = 1; i < maxHor; ++i){
res[i][0] = obstacleGrid[i][0] == 1 ? 0 : res[i - 1][0];
}
for(int j = 1; j < maxVer; ++j){
res[0][j] = obstacleGrid[0][j] == 1 ? 0 : res[0][j - 1];
}
for(int i = 1; i < maxHor; ++i){
for(int j = 1; j < maxVer; ++j){
res[i][j] = obstacleGrid[i][j] == 1 ? 0 : res[i - 1][j] + res[i][j - 1];
}
}
return res[maxHor - 1][maxVer - 1];
}
};


java版本的代码如下所示:

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid.length == 0 || obstacleGrid[0].length == 0)
return 0;
int [][] grid = new int [obstacleGrid.length][obstacleGrid[0].length];
grid[0][0] = obstacleGrid[0][0]==1 ? 0 : 1;
for(int i = 1; i < obstacleGrid.length; ++i){
grid[i][0] = obstacleGrid[i][0]==1? 0 : grid[i-1][0];
}
for(int i = 1; i < obstacleGrid[0].length; ++i){
grid[0][i] = obstacleGrid[0][i]==1? 0 : grid[0][i-1];
}
for(int i = 1; i < obstacleGrid.length; ++i){
for(int j = 1; j < obstacleGrid[0].length; ++j){
grid[i][j] = obstacleGrid[i][j]==1? 0 : (grid[i-1][j] + grid[i][j-1]);
}
}
return grid[obstacleGrid.length-1][obstacleGrid[0].length-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: