[英]How do i return boolean from recursive method?
This method finds a path from top left to bottom right in a given labyrinth. 此方法在给定的迷宫中找到从左上角到右下角的路径。 I have checked and my method finds me a path but i cant get it to return true when its done.
我已经检查过,我的方法找到了一条路径,但是完成后我无法让它返回true。 It prints out "You made it" from my if-statement, but it dosent returns true.
它从我的if语句中打印出“您成功做到了”,但是它返回true。
if((x0 == x1) && (y0 == y1)) {
System.out.println(l);
System.out.println("You made it");
return true;
}
I know it's something with recursive and that you return values in a diffrent way. 我知道这是递归的,并且您以不同的方式返回值。 I still dont have a clue how to return my value correctly.
我仍然不知道如何正确返回我的值。
Heres the method: 继承方法:
public static boolean findPath(int x0, int y0, int x1, int y1, Labyrinth l) {
l.setMark(x0, y0, true);
if((x0 == x1) && (y0 == y1)) {
System.out.println(l);
System.out.println("You made it");
return true;
}
//is it possible to move in any new direction? if yes, then move
if(l.canMove(Labyrinth.Direction.RIGHT, x0, y0) && !l.getMark(x0+1, y0) && !hasBeen[x0+1][y0]){
findPath(x0+1, y0, x1, y1, l);
}else if(l.canMove(Labyrinth.Direction.DOWN, x0, y0) && !l.getMark(x0, y0+1)&& !hasBeen[x0][y0+1]){;
findPath(x0, y0+1, x1, y1, l);
}else if(l.canMove(Labyrinth.Direction.UP, x0, y0) && !l.getMark(x0, y0-1)&& !hasBeen[x0][y0-1]){
findPath(x0, y0-1, x1, y1, l);
}else if(l.canMove(Labyrinth.Direction.LEFT, x0, y0) && !l.getMark(x0-1,y0)&& !hasBeen[x0-1][y0]){
findPath(x0-1, y0, x1, y1, l);
}else{
//go back one step and set hasBeen true for this coordinate
l.setMark(x0,y0,false);
hasBeen[x0][y0]=true;
if(l.getMark(x0+1, y0)){
findPath(x0+1, y0, x1, y1, l);
}else if(l.getMark(x0, y0+1)){
findPath(x0, y0+1, x1, y1, l);
}else if(l.getMark(x0, y0-1)){
findPath(x0, y0-1, x1, y1, l);
}else if(l.getMark(x0-1,y0)){
findPath(x0-1, y0, x1, y1, l);
}
}
return false;
}
} }
You need to propagate the return statements. 您需要传播return语句。 Instead of just calling
findPath(x0+1, y0, x1, y1, l);
不仅仅是调用
findPath(x0+1, y0, x1, y1, l);
recursively, you need to do: 递归地,您需要执行以下操作:
return findPath(x0+1, y0, x1, y1, l);
Also, with that, you can do away with all the 'else' statements. 此外,这样一来,您就可以消除所有的“ else”语句。 Just the if's will suffice.
只要是就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.