题目描述:
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.
("Unique Paths"的后续:
现在考虑在网格中添加一些障碍物。
会有多少独特的路径?
在网格中,障碍物和空白分别被标记为1和0。
例如,
有一个障碍,在一个九宫格中如下图所示。
[
[0,0,0],
[0,1,0],
[0,0,0]
]
唯一路径的总数是2。
注:m和n最多为100。)
思路:和Unique Paths一样,只需要将障碍处的DP设置为0就可以.
public class Unique_Paths_II {
public static int uniquePathsWithObstacles(int[][] obstacleGrid)
{
if(obstacleGrid.length==0||obstacleGrid[0].length==0)
return 0;
int DP[][] = new int[obstacleGrid.length][obstacleGrid[0].length];
DP[0][0] = 1;
for(int i=0;i<obstacleGrid.length;i++)
{
for(int j=0;j<obstacleGrid[0].length;j++)
{
if(obstacleGrid[i][j]==1)
{
DP[i][j] = 0;
continue;
}
if(i-1>=0)
DP[i][j] += DP[i-1][j];
if(j-1>=0)
DP[i][j] += DP[i][j-1];
}
}
return DP[obstacleGrid.length-1][obstacleGrid[0].length-1];
}
public static void main(String[] args) {
int[][] obstacleGrid = {{0,0,0},{0,1,0},{0,0,0}};
System.out.println(uniquePathsWithObstacles(obstacleGrid));
}
}