【发布时间】:2015-01-11 17:43:17
【问题描述】:
提前感谢您的帮助,基本上我正在尝试退出 void 方法的递归,但是在 return 语句之前和之后发生了一些有趣的事情。基本上该程序是通过迷宫找到路径,所以一次它打印 YES , return 语句应该防止 rec(int x,int y) 方法的任何进一步递归,但是在打印 YES 之后它仍然打印,所以这就是我的问题。所以除了打印 YES 和 NO 之外,所有其他 println 语句基本上将它们用于调试,因此如果您观察到,在打印 YES 之前 println 语句将“x”打印为 4,将“y”打印为 1,但在 return 语句之后,它们的值已更改为 2 和 1,当有没有进一步的代码来操纵它们的值。
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;
}
}
输出如下
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
【问题讨论】:
-
我相信 //code 部分在这里也很重要。目前该方法甚至不是递归的;)
-
更新了代码@MrHug
-
那么 main() 中的那个呢?
-
很想尝试 System.exit(0),但问题需要多个用例,所以不得不求助于返回,但我之前从未遇到过这样的事情
-
对这个问题的格式稍加努力可能会很方便(特别是缩进)。