Reputation: 3
thanks in advance for your help, basically i'm trying to exit the recursion of a void method but some funny things are happening before and after the return statement.basically the program is to find a path through a maze, so once it prints YES , the return statement should prevent any further recursion of the rec(int x,int y) method, but it still prints after printing YES , so thats my question.so except for printing YES and NO all the other println statements basically used them for debugging , so if you observe, before printing YES the println statements print 'x' as 4 and 'y' as 1, but then after return statement their values have changed to 2 and 1, how is that possible when there is no further code to manipulate their values.
static int x,y,fx,fy;
static char g[][]={ //your maze array , # represents wall and . represents path};
static Stack<Integer>stackx=new Stack<Integer>();
static Stack<Integer>stacky=new Stack<Integer>();
// both of the stacks are used for reverting changes int he maze to original
public static void main(String args[])
{
x=y=0;
for(int i=0;i<g.length;i++)
{
for(int j=0;j<g[i].length;j++)
{
if(g[i][j]=='S')
{
x=j;
y=i;
}
else if(g[i][j]=='G')
{
fx=j;
fy=i;
}
}
}
rec(x,y);
System.out.println("HEllooooooo");
}
public static void rec(int x,int y)
{
try
{
System.out.println(x+" "+y+" "+check);
if(x==fx && y==fy)
{
System.out.println("YES");
check=true;
x=y=0;
return;
}
System.out.println(x+" "+y+" "+check);
if(check==false)
{
revert();// reverts maze back to original
change(); // slides walls in the maze
for(int i=0;i<g.length;i++)
{
for(int j=0;j<g[0].length;j++)
{
System.out.print(g[i][j]);
}
System.out.println("");
}
if(!valid(x,y+1))
{
if(!((y+1)>(g.length-1)))
{
g[y+1][x]='#';
}
}
else
{
rec(x,y+1);
}
if(!valid(x+1,y))
{
if(!((x+1)>(g[0].length-1)))
{
g[y][x+1]='#';
}
}
else
{
rec(x+1,y);
}
if(!valid(x-1,y))
{
if(!((x-1)>=0))
{
g[y][x-1]='#';
}
}
else
{
rec(x-1,y);
}
if(!valid(x,y-1))
{
if(!((y-1)>=0))
{
g[y-1][x]='#';
}
}
else
{
rec(x,y-1);
}
}
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("NO");
return;
}
}
and the out put is as follows
4 1 false
YES // output is correct and should end but it continues//
2 1 true //x and y values change from 4,1 to 2,1 even with no code to manipulate them
2 1 true
3 0 true
3 0 true
4 0 true
4 0 true
NO
1 1 true
1 1 true
0 1 true
0 1 true
NO
HEllooooooo
Upvotes: 0
Views: 114
Reputation: 31290
If hitting fx,fy is the ultimate goal, then:
boolean rec( int x, int y )
After "YES" is printed:
return true;
All recursive calls rec( ..., ... ) should be replaced by
if( rec( ..., ... ) ) return true;
This should bring you out of the recursion.
And the last return:
return false;
Upvotes: 1