码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Unique Paths II

时间:2014-11-07 20:56:34      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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. 初始化第一行第一列时考虑有障碍的影响。一旦行或列中出现了障碍格子,后面的格子都不可达。
  2. 在更新到达(i,j)格子时,要注意查看(i,j-1)和(i-1,j)是否是障碍格子,并分别处理。

代码:

int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {  //c++
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        int array[m][n];  
        
        //init   
        bool haveObs = false;
        for(int i = 0; i < n; i++){  
            if(obstacleGrid[0][i] == 0 && !haveObs){
                array[0][i] = 1;  
                continue;   
            }
            else if(obstacleGrid[0][i] == 1){
                haveObs = true;
            }
            array[0][i] = 0;
        }
        
        haveObs = false;
        for(int i = 0; i < m; i++) { 
            if(obstacleGrid[i][0] == 0 && !haveObs){
                array[i][0] = 1;
                continue;   
            }
            else if(obstacleGrid[i][0 ==1]){
                haveObs = true;    
            } 
            array[i][0] = 0;
        }
              
        for(int i = 1; i < m; i++)  
            for(int j = 1; j < n; j++){ 
                array[i][j] = 0;
                if(obstacleGrid[i][j] == 1)
                    continue;
                if(obstacleGrid[i-1][j] == 0)
                    array[i][j] += array[i-1][j];
                if(obstacleGrid[i][j-1] == 0)
                    array[i][j] +=array[i][j-1];  
            }  
        return array[m-1][n-1];  
    }



[leetcode]Unique Paths II

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/40897285

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!