vendredi 20 juillet 2018

Find if path exist or not in maze c++

My code is giving me runtime error. I can't figure it out how to resolve it? It's not even working for smaller matrix 4 X 4 . Matrix size for the problem is not more than 20 x 20.

Code:

#include <iostream>
using namespace std;
int a[20][20];
bool findpath(int ar[][20],int i,int j,int size)
{
    if (ar[i][j]==0 || i>(size-1) || j>(size-1) || i<0 || j<0)
        return false;
    if (ar[i][j]==2)
        return true;
    if ((findpath(ar,i+1,j,size)) || (findpath(ar,i,j+1,size)) 
    || (findpath(ar,i-1,j,size)) || (findpath(ar,i,j-1,size)))
        return true;
    return false;
}
int main() {
    int t;
    cin>>t;
    while(t--)
    {   int n;
        cin>>n;

        int r,c;

        //size = n;
        for(int i =0 ;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                cin>>a[i][j];
                if (a[i][j]==1)
                   { r=i;
                    c=j;
                   }
            }

        }
        //cout<<r<<c;
        bool b = findpath(a,r,c,n);
        if (b)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;

    }
    return 0;
}

Input:

1
4
3 0 0 0 0 3 3 0 0 1 0 3 0 2 3 3 

Output:

YES

But I am getting Segmentation Fault (SIGSEGV)

Aucun commentaire:

Enregistrer un commentaire