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

63. Unique Paths II 类别:动态规划 难度:medium

2016-12-26 16:41 387 查看
题目:

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
.

思路:

这题的思路与 62
Unique Paths 大致相同。 唯一的不同在于,如果某个方格有障碍,那么记录每个方格路径数的数组 res[] 在该单元内被置为
0 。 
方格左上角和右下角只要有一个为障碍,那么结果都是 0. 

程序:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();

vector<vector<int>> dp(m,vector<int>(n,0));

for(int i = n - 1;i >= 0&&obstacleGrid[m - 1][i] != 1;i--)
dp[m - 1][i] = 1;

for(int i = m - 1;i >= 0&&obstacleGrid[i][n - 1] != 1;i--)
dp[i][n - 1] = 1;

for(int i = m - 2;i >= 0;i--)
{
for(int j = n - 2;j >= 0;j--)
{
if(obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else
dp[i][j] = dp[i + 1][j] + dp[i][j + 1];
}
}
return dp[0][0];

}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: