Unique Paths II in C++


Suppose there is a robot is located at the top-left corner of a n x m grid (n rows and m columns). The robot can only move either down side or right side at any point in time. The robot wants to reach the bottom-right corner of the grid (marked 'END in the diagram below).

Some cell in the grid is marked, that will be considered as obstacles. So we have to find how many possible unique paths are there? For example if the grid is like [[0,0,0],[0,1,0],[0,0,0]], then the grid will be like below −

Robo


Obs


END

The output will be 2, So there are total 2 different ways to reach from start position to the end position. These paths are −

  1. Right → Right → Down → Down
  2. Down → Down → Right → Right

Let us see the steps −

  • a := number of rows, b := number of columns
  • if grid[a – 1,b - 1] is non zero, then return 0
  • create one table whose order is a x b, and name is DP
  • for i := b – 1 down to 0
    • if grid[a – 1, i], then break, otherwise DP[a – 1, i] := 1
  • for i := a – 1 down to 0
    • if grid[i, b - 1], then break, otherwise DP[i, b – 1] := 1
  • for i := a – 2 down to 0
    • for j := b – 2 down to 0
      • DP[i, j] := DP[i + 1, j] + DP[i, j + 1] when grid[i, j] is 0, otherwise 0
  • return DP[0, 0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
      int a = obstacleGrid.size();
      int b = obstacleGrid[0].size();
         if(!a || !b) return 0;
      if(obstacleGrid[a - 1][b - 1])return 0;
      vector < vector <lli> > dp(a, vector <lli>(b));
      for(int i = b - 1; i >= 0; i--)if(obstacleGrid[a-1][i]) break; else dp[a-1][i] = 1;
      for(int i = a - 1; i >= 0; i--)if(obstacleGrid[i][b - 1]) break; else dp[i][b-1] = 1 ;
      for(int i = a-2; i >= 0; i--){
         for(int j = b-2 ; j >= 0; j--)dp[i][j] = !obstacleGrid[i][j]? dp[i+1][j] + dp[i][j+1] : 0;
      }
      return dp[0][0];
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{0,0,0},{0,1,0},{0,0,0}};
   cout << ob.uniquePathsWithObstacles(v);
}

Input

[[0,0,0],[0,1,0],[0,0,0]]

Output

2

Updated on: 04-May-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements