I am writing a program to find all unique paths from 0,0 to the bottom right corner of a matrix, while only moving on open spaces (0) and not obstacles(1)
I used recursion to check each path, allowing the program to go up, down, right, left.
Every time I run the program, there is segmentation fault. Can someone help me figure out why? I can't find the solution after a long time.
#include<bits/stdc++.h>
using namespace std;
int UniquePathHelper(int i, int j, int r, int c, vector<vector<int>>& A){
// boundary condition or constraints
if(i == r || j == c || i < 0 || j < 0){
return 0 ;
}
if(A[i][j] == 1){
return 0 ;
}
// base case
if(i == r-1 && j == c-1){
return 1 ;
}
return UniquePathHelper(i+1, j, r, c, A) +
UniquePathHelper(i, j+1, r, c, A) +
UniquePathHelper(i-1, j, r, c, A) +
UniquePathHelper(i, j-1, r, c, A) ;
}
int uniquePathsWithObstacles(vector<vector<int>>& A)
{
int r = A.size(), c = A[0].size();
return UniquePathHelper(0, 0, r, c, A) ;
}
// Driver code
int main()
{
vector<vector<int>> A = { { 0, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 0 } };
cout << uniquePathsWithObstacles(A) << " \n";
}```