题目描述:
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 as1and0respectively 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 is2.
Note: m and n will be at most 100.
递归例程:
public class Solution {
public int uniquePathsWithObstacles(int[][] grid) {
if(grid == null||grid.length == 0||grid[0].length == 0)
return 0;
int row=grid.length;
int col=grid[0].length;
return help(grid,0,0,row,col);
}
public int help(int[][] grid,int i,int j,int row,int col)
{
if(i == row-1&&j == col-1)
return 1;
if(grid[i][j] == 1)
return 0;
if(i == row-1)
return help(grid,i,j+1,row,col);
if(j == col-1)
return help(grid,i+1,j,row,col);
else
return help(grid,i+1,j,row,col)+help(grid,i,j+1,row,col);
}
}DP例程:
public int uniquePathsWithObstacles(int[][] grid) {
if(grid == null||grid.length == 0||grid[0].length == 0)
return 0;
int row=grid.length;
int col=grid[0].length;
int[][] dp=new int[row][col];
dp[row-1][col-1]=1;
if(grid[row-1][col-1] == 1)
dp[row-1][col-1]=0;
//最下行初始化
for(int j=col-2;j>=0;j--)
{
if(grid[row-1][j] == 1)
dp[row-1][j]=0;
else
dp[row-1][j]=dp[row-1][j+1];
}
//最右行初始化
for(int i=row-2;i>=0;i--)
{
if(grid[i][col-1] == 1)
dp[i][col-1]=0;
else
dp[i][col-1]=dp[i+1][col-1];
}
//general
for(int i=row-2;i>=0;i--)
{
for(int j=col-2;j>=0;j--)
{
if(grid[i][j] == 1)
dp[i][j]=0;
else
dp[i][j]=dp[i+1][j]+dp[i][j+1];
}
}
return dp[0][0];
}
本文介绍了一种算法,用于计算在存在障碍的情况下从起点到终点的不同路径数量。通过使用递归和动态规划两种方法来解决这一问题,递归方法直接根据问题定义进行递归求解,而动态规划方法则构建一个矩阵逐步计算出最终结果。
888

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



