Given a N X N matrix (M) filled with 1, 0, 2, 3. The task is to find whether there is a path possible from source to the destination while traversing through blank cells only. You can traverse up, down, right, and left. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday 14 July 2020

Given a N X N matrix (M) filled with 1, 0, 2, 3. The task is to find whether there is a path possible from source to the destination while traversing through blank cells only. You can traverse up, down, right, and left.


Given a N X N matrix (M) filled with 1, 0, 2, 3. The task is to find whether there is a path possible from source to the destination while traversing through blank cells only. You can traverse up, down, right, and left.
  1. A value of cell 1 means Source.
  2. A value of cell 2 means Destination.
  3. A value of cell 3 means Blank cell.
A value of cell 0 means Blank Wall.
Note: there are only a single source and a single destination

For each test case in a new line print 1 if the path exists from source to destination else print 0.

#include <bits/stdc++.h>
using namespace std;
#define N 21
int check(int i,int j,int n,int a[N][N])
{
// if i and j outoff index or a[i][j] is zero then return 0
    if(i<0||j<0||i>=n||j>=n||a[i][j]==0) 
    return 0;
// if a[i][j] is destination when its value is 2
    if(a[i][j]==2)
    return 1;
    a[i][j]=0;
// here return all combination of  check value with or logic
   return  check(i,j+1,n,a) || check(i,j-1,n,a)||check(i-1,j,n,a)||check(i+1,j,n,a);
    
}

int main() {
//code
int t;
cin>>t;
while(t--)
{
    int n,x,y,d,m,l;
    cin>>n;
    int a[N][N];
    
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<n;++j)
        {
            cin>>a[i][j];
// finding the source index when a[i][j] is 1

            if(a[i][j]==1)
            {
                x=i,y=j;
            }
            
        }
    }
    
    cout<<check(x,y,n,a)<<endl;
   
}
return 0;
}