1. 程式人生 > >[leetcode]Unique Paths II

[leetcode]Unique Paths II

出現 acl ive leetcode tracking there pat sni leet

問題描寫敘述:

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