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

Unique Paths II - LeetCode 63

2015-05-07 21:04 211 查看
题目描述:

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.

分析:接着上一题,稍作修改。由于有些格子“坏掉”,因为需要修改动态二维数组vec的初始化值。此处只需初始化第一行和第一列的值。

过程如下:

1. 首先对于左上角的格子,如果obstacleGrid[0][0]为1,表示该格子不能走,那么vec[0][0] = 0;

2. 对于首行元素从j(j>0)开始,如果obstacleGrid[0][j] = 0; 表示该格子可以走,则vec[0][j] = vec[0][j-1],否则vec[0][j] = 0

对于首列元素从i(i>0)开始,如果obstacleGrid[i][0] = 0; 表示该格子可以走,则vec[i][0] = vec[i-1][0],否则vec[i][0] = 0

3. 计算源起点到每个格子的路径总数:

遍历obstacleGrid,如果obstacleGrid[i][j] = 1,表示该格子可以走,那么vec[i][j] = vec[i-1][j] + vec[i][j-1];否则vec[i][j] = 0

最后返回vec[i][j]即可

以下是C++实现代码,实现过程中要注意处理输入为空的情况,以及源起点格子不可通过等特殊情况:
/*/////////////7ms///*/
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> vec(m,vector<int>(n));
if(obstacleGrid.empty() || obstacleGrid[0][0] == 1)
return 0;
vec[0][0] = 1;
if(m == 1 && n == 1)
return vec[m-1][n-1];
for(int i = 1; i != n; i++)  /*初始化第一列*/
{
if(obstacleGrid[0][i] == 0)
vec[0][i] = vec[0][i-1];
else
vec[0][i] = 0;
}
for(int i = 1; i != m; i++)  /*初始化第一行*/
{
if(obstacleGrid[i][0] == 0)
vec[i][0] = vec[i-1][0];
else
vec[i][0] = 0;
}
/*递推计算源起点格子到其余每一个格子的路径数*/
for(int i = 1; i != m; i++)
{
for(int j = 1; j != n; j++)
{
if(obstacleGrid[i][j] == 0)
vec[i][j] = vec[i-1][j] + vec[i][j-1];
else
vec[i][j] = 0;
}
}
return vec[m-1][n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: