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
.
m and n will be at most 100.
Tags Expand
原题地址:http://www.lintcode.com/en/problem/unique-paths-ii/
这道题是unique-path问题的一个follow up。题目比较有意思就是说如果在Unique-path问题中有一个障碍obstacle那么不同的走法一共有多少个。题目用矩阵中的1表明障碍。
其实这道题核心的DP方程没有发生任何变化。对于任何最优解经过的点OPT[i][j]有且仅有可能通过它上面一个顶点grid[i-1][j]或者是左边的顶点grid[i][j-1]走到。所以DP方程仍然是
OPT[i][k] = OPT[i-1][k]+OPT[i][k-1];
这道题需要做的就是在给OPT矩阵循环赋值的时候做一些判断和考虑。如果grid矩阵中有一个点不可达。那么在OPT数组中其值为0,因为根本不可能有最优解的路径经过该顶点。并且在初始化OPT数组的时候需要考虑一个情况。如果obstacle出现在grid数组的两条边界中,一旦发现有Obstacle在边界中,改Obstacle之后的点都不用赋值。应为根本无法走到。
public class Solution {
/**
* @param obstacleGrid: A list of lists of integers
* @return: An integer
*/
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
// write your code here
int m = obstacleGrid.length;
int n = obstacleGrid[m-1].length;
if( m == 0 ){
for(int i = 0;i<n; i++){
if(obstacleGrid[i][0]==0){
return 0;
}
return 1;
}
}
if( n == 0 ){
for(int i = 0;i<m; i++){
if(obstacleGrid[0][i]==0){
return 0;
}
return 1;
}
}
int[][]OPT = new int[m][n];
for( int i = 0; i<m; i++){
if(obstacleGrid[i][0] != 1){
OPT[i][0] = 1;
}
else break;
}
for( int i = 0; i<n; i++){
if(obstacleGrid[0][i] != 1){
OPT[0][i] = 1;
}
else break;
}
for(int i = 1;i<m; i++){
for(int k = 1;k<n;k++){
if(obstacleGrid[i][k]==1){
OPT[i][k] =0;
}
else{
OPT[i][k] = OPT[i-1][k]+OPT[i][k-1];
}
}
}
return OPT[m-1][n-1];
}
}