程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> (LeetCode OJ) 63. Unique Paths II

(LeetCode OJ) 63. Unique Paths II

編輯:C++入門知識

(LeetCode OJ) 63. Unique Paths II


 

63. Unique Paths II

My Submissions   Total Accepted: 55136 Total Submissions: 191949 Difficulty: Medium

 

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.

 

Subscribe to see which companies asked this question

Hide Tags Array Dynamic Programming Hide Similar Problems (M) Unique Paths  
//思路首先:
//此題與原問題相較,變得是什麼?
//1,此障礙物下面和右邊將不在獲得來自於此的數量,也可以理解為貢獻為0
//2,有障礙的地方也將無法到達(這一條開始時沒想到,總感覺leetcode題目意思不願意說得明了),可能輸數直接為0
class Solution {
public:
    int uniquePathsWithObstacles(vector>& obstacleGrid) {
        int m=obstacleGrid.size();
        int n=obstacleGrid[0].size();
        vector< vector >  result(m+1);   
        for(int i=0;i <=m ;i++)   
            result[i].resize(n+1);//設置數組的大小m+1行,n+1列   
        //初始化一定要正確,否則錯無赦    
        result[1][1]= obstacleGrid[0][0]==1? 0:1;    
        for(int i=2;i<=n;i++)  
            result[1][i]=obstacleGrid[0][i-1]==1?0:result[1][i-1];//由上一次來推到  
        for(int i=2;i<=m;i++)  
            result[i][1]=obstacleGrid[i-1][0]==1?0:result[i-1][1];  
            
        for(int i=2;i<=m;i++)  
            for(int j=2;j<=n;j++)  
                result[i][j]=obstacleGrid[i-1][j-1]==1?0:result[i-1][j]+result[i][j-1];  //一旦當前有石頭就無法到達,直接置零
            
        return result[m][n];
    }
};

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved