Rat in a maze- problem

https://ide.codingblocks.com/s/55453

how to produce correct ouput for this problem ?

Hey Yukti, your code is not correct, make a matrix to keep the track of visited paths and before making a call in right direction first put an if check if(j+1<=n && !visited[i][j+1]) and before making a call in down direction first put an if check if(i+1<=m && !visited[i+1][j]).

https://ide.codingblocks.com/s/56059

1 Like

#include<bits/stdc++.h>
using namespace std;
int flag;
bool findPath(char soln[][1000],char maze[][1000],int i,int j,int m,int n){
if(i==m-1&&j==n-1){
soln[i][j]=‘1’;
if(flag==0){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cout<<soln[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
flag=1;
}
soln[i][j]=‘0’;
return true;
}
if(i==m||j==n)
return false;
if(maze[i][j]==‘X’)
return false;

soln[i][j]='1';

bool right=findPath(soln,maze,i,j+1,m,n);
bool left=findPath(soln,maze,i+1,j,m,n);

soln[i][j]='0';

if(left||right)
	return true;
return false;

}
int main(){
flag=0;
int n,m;
cin>>n>>m;
char maze[1000][1000];
char soln[1000][1000];
memset(soln,‘0’,sizeof(soln));
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>maze[i][j];
bool p=findPath(soln,maze,0,0,n,m);
if(!p)
cout<<"-1"<<endl;
return 0;
}

HEY SOMEONE PLZ HELP ME WITH THIS CODE.
IN THE CASE 0 IT IS GIVING A TLE REST ALL CASES ARE WORKING FINE.
ALSO THIS CODE IS FOR PRINTING ALL THE COMBINATIONS POSSIBLE AND I WANT ONLY 1ST SUCH POSSIBLE COMBINATION. I USED A TRICK OF FLAG VARIABLE FOR NOT PRINTING THE REST COMBINATION BUT THAT SHOULD BE AVOIDED SO IF ANYONE CAN LET ME KNOW WHERE I NEED TO CHANGE TO TAKE THE CONTROLL BACK TO MAIN AFTER 1ST PRINTING.