Unique Paths II
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.
解析
此题是Unique Paths的升级版,即有的地方是不可达的。
递推公式为:
f(x,y)=(f(x−1,y)+f(x,y−1))∗(1−obstacleGrid[x][y])
其中,obstacleGrid为题中的二维矩阵。
代码:DP
版本一
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize) {
//判断指针,和其他参数的合理性,略
int *fx = (int*)malloc(obstacleGridColSize*sizeof(int));
int f=1;
for(int i=0;i<obstacleGridColSize;i++){
if(f==1&&obstacleGrid[0][i]==1){
f=0;
}
fx[i]=f;
}
f=1-obstacleGrid[0][0];
for(int i=1;i<obstacleGridRowSize;i++){
if(f==1&&obstacleGrid[i][0]==1){
f=0;
}
fx[0]=f;
for(int j=1;j<obstacleGridColSize;j++){
fx[j]+=fx[j-1];
fx[j]*=(1-obstacleGrid[i][j]);
}
}
int res= fx[obstacleGridColSize-1];
free(fx);
return res;
}
版本二
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize) {
//判断指针,和其他参数的合理性,略
int *fx = (int*)malloc(obstacleGridColSize*sizeof(int));
memset(fx,0,obstacleGridColSize*sizeof(int));
fx[0]=1;
for(int i=0;i<obstacleGridRowSize;i++){
for(int j=0;j<obstacleGridColSize;j++){
fx[j]=(fx[j]+fx[j-1])*(1-obstacleGrid[i][j]);
}
}
int res= fx[obstacleGridColSize-1];
free(fx);
return res;
}
本文深入探讨了UniquePaths问题的进阶版本,在网格中包含障碍物的情况下,如何计算唯一的路径数量。通过引入递推公式,文章详细解释了在遇到障碍物时如何调整路径计数。实例分析结合代码实现,旨在帮助读者理解并解决类似问题。
1143

被折叠的 条评论
为什么被折叠?



