-
Notifications
You must be signed in to change notification settings - Fork 492
/
UniquePaths2.cpp
58 lines (43 loc) Β· 1.94 KB
/
UniquePaths2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//UNIQUE PATHS II
//LINK OF THE PROBLEM :- https://leetcode.com/problems/unique-paths-ii/
#include<bits/stdc .h>
using namespace std;
int totalPaths(int currRow,int currCol,int targetRow,int targetCol, vector<vector<int>>&obstacleGrid,vector<vector<int>>&v)
{
//base conditions
if(currRow == targetRow && currCol == targetCol && obstacleGrid[currRow][currCol]==0) //valid path
return 1;
if(currRow<0||currCol<0||currRow>targetRow||currCol>targetCol|| obstacleGrid[currRow][currCol]==1) //invalid path
return 0;
//if value is already present in the vector v ,then extract from it, no need to make recursive calls for it
if(v[currRow][currCol]!=-1) return v[currRow][currCol];
//exploring the two possibilities :-1.right movement 2.downward movement
int right = totalPaths(currRow,currCol 1,targetRow,targetCol,obstacleGrid,v); //when the robot moves right
int down = totalPaths(currRow 1,currCol,targetRow,targetCol,obstacleGrid,v); //when the robot moves down
//storing the answer for the current coordinate in v,so that we can use it in future
v[currRow][currCol] = (right down);
return v[currRow][currCol];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
int r = obstacleGrid.size(); //no. of rows
int c = obstacleGrid[0].size(); //no. of columns
vector<vector<int>>v(r,vector<int>(c,-1));
//if we have a 1X1 matrix and obstacleGrid[0][0]=1,then we don't have any valid path
if(r==1 && c==1 && obstacleGrid[r-1][c-1]==1) return 0;
return totalPaths(0,0,r-1,c-1,obstacleGrid,v);
}
int main()
{
int m,n;
cin>>m; //total number of rows
cin>>n; //total number of columns
vector<vector<int>>obstacleGrid(m,vector<int>(n,0));
for(int i=0;i<m;i )
{
for(int j=0;j<n;j )
cin>>obstacleGrid[i][j];
}
cout<< uniquePathsWithObstacles(obstacleGrid) ;
return 0;
}