Unique Path II

9 篇文章 0 订阅
8 篇文章 0 订阅
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 0respectively in the grid.

Example

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.

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];
            
        
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值