| 1 | class Solution { |
| 2 | public: |
| 3 | int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { |
| 4 | |
| 5 | |
| 6 | vector<vector<int>> dp(obstacleGrid.size(),vector<int>(obstacleGrid[0].size(),0)); // empty grid for memoization |
| 7 | int flag1=0; |
| 8 | int flag2=0; |
| 9 | |
| 10 | for(int i=0;i<dp.size();i++){ //examining first column |
| 11 | if(obstacleGrid[i][0]!=1 && flag1==0){ |
| 12 | dp[i][0]=1; //cells in the starting column can be visited only by one way |
| 13 | } |
| 14 | else{ |
| 15 | dp[i][0]=0; //since there is an obstacle in the way, we cannot reach this point |
| 16 | flag1=1; //set flag value since we cannot access any further points past the obstacle |
| 17 | } |
| 18 | } |
| 19 | for(int i=0;i<dp[0].size();i++){ //examining first row |
| 20 | if(obstacleGrid[0][i]!=1 && flag2==0){ |
| 21 | dp[0][i]=1; //cells in the starting row can be visited only by one way |
| 22 | } |
| 23 | else{ |
| 24 | dp[0][i]=0; //since there is an obstacle in the way, we cannot reach this point |
| 25 | flag2=1; //set flag value since we cannot access any further points past the obstacle |
| 26 | } |
| 27 | } |
| 28 | if(dp[0][0]==0){ // if obstacle is placed at the starting point |
| 29 | return 0; |
| 30 | } |
| 31 | |
| 32 | for(int i=1;i<dp.size();i++){ |
| 33 | for(int j=1;j<dp[0].size();j++){ |
| 34 | if(obstacleGrid[i][j]==1){ |
| 35 | dp[i][j]=0; // since it is an obstacle, it cannot be reached |
| 36 | } |
| 37 | else{ |
| 38 | dp[i][j]=dp[i-1][j]+dp[i][j-1]; // no. of ways of reaching current cell= no. of ways of reaching the cell above+number of ways of reaching left cell |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | return dp[obstacleGrid.size()-1][obstacleGrid[0].size()-1]; |
| 44 | } |
| 45 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected