Hey guys
Icame across a weird situation wherein I had to use System.exit(1) in place of return,
although the output in both cases should be same, the output im getting with return statement is giving me the wrong result while the one with System.exit(1) is giving me the correct result ;
the program here uses recursion to solve the maze (0's are the paths, 1's are the walls) , the mouse is in index 91 of the 1 D array (we can use 2D array also , but i did this so as to avoid some unneccessary code), the exit is index 33;EVERY TIME THE METHOD EXITCELL IS CALLED: the mouse moves along the corresponding 0s; in case of the dead end it retraces its path to the entry point of the dead end, and then chosses another path
class MazeMouse{
private int[] maze = {
/* 0 1 2 3 4 5 6 7 8 9 10
/*00*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/*11*/ 1, 0, 0, 0 , 0, 0 , 1, 0 , 0, 0 , 1,
/*22*/ 1, 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 1,
/*33*/ 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1,
/*44*/ 1 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 1,
/*55*/ 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1,
/*66*/ 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1,
/*77*/ 1 , 1 , 1 , 1 , 1 , 0, 1 , 0 , 0 , 0, 1,
/*88*/ 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 1,
/*99*/ 1 , 0, 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1,
/*110*/ 1 , 1 , 1 , 1, 1 , 1, 1 , 1, 1 , 1, 1
};
private int start = 91;
private int end = 33;
private int moves[] = {-1,-11,1,11}; // left ,up ,right ,down;
private int cameFrom[] = new int[121];
public void exitcell(int current)
{
System.out.println(current+" ");
if(current == end){
System.out.println("Exit Reached");
System.exit(1);
return ;
}
for(int i = 0 ; i < 4 ; i++)
{
int next = current+moves[i];
if(maze[next]!= 1 && cameFrom[current]!= next)
{
cameFrom[next] = current;
exitcell(next);
}
}
return;
}
public static void main(String args[]){
MazeMouse a = new MazeMouse();
a.exitcell(a.start);
}
}