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

63. Unique Paths II,63uniquepathsii

編輯:C++入門知識

63. Unique Paths II,63uniquepathsii


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.

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
 4         if(obstacleGrid.empty() || obstacleGrid[0].empty()){
 5             return 0;
 6         }
 7         int row = obstacleGrid.size();
 8         int col = obstacleGrid[0].size();
 9         
10         int dp[row][col];
11         
12         dp[0][0] = (obstacleGrid[0][0] == 0 ? 1 : 0);
13         
14         for(int i = 1; i < row; i++){
15             dp[i][0] = ((dp[i-1][0] == 1 && obstacleGrid[i][0] == 0)? 1 : 0);
16         }
17         
18         for(int j = 1; j < col; j++){
19             dp[0][j] = ((dp[0][j-1] == 1 && obstacleGrid[0][j] == 0)? 1: 0);
20         }
21         
22         for(int i = 1 ; i < row; i++){
23             for(int j = 1 ; j < col;j++){
24                 if(obstacleGrid[i][j] == 1){
25                     dp[i][j] = 0;
26                 }else{
27                     dp[i][j] = dp[i-1][j]+dp[i][j-1];
28                 }
29             }
30         }
31         
32         return dp[row-1][col-1];
33     }
34 };

 

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