leetcode_63. 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.

跟之前的Unique Paths相近。只不過有可能這個地方是走不通的。所以就需要多加一個判斷。即如果這個地方走不通那麼到這個地方的路數就是0;走得通再將上面即左邊的路數加進來。

代碼如下:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        
        int grid[m][n] = {0};
        if(obstacleGrid[0][0] == 1){
             grid[0][0] = 0;  
        }else{
            grid[0][0] = 1;
        }
          
 
        for(int j = 1; j < n; ++j){  
            if(obstacleGrid[0][j] == 0 && grid[0][j-1]!= 0)  {
                grid[0][j] = 1;
            }else{
                grid[0][j] = 0;
            }
            
        }  
        for(int i = 1; i < m; ++i){  
            if(obstacleGrid[i][0] == 0 && grid[i-1][0]!= 0)  {
                grid[i][0] = 1;
            }else{
                grid[i][0] = 0;
            }  
        }  
        for(int i = 1; i < m; ++i){  
            for(int j = 1; j < n; ++j){
                if(obstacleGrid[i][j] == 0){
                    grid[i][j] =grid[i-1][j] + grid[i][j-1];
                }
            }  
        }  
    return grid[m-1][n-1]; 
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章