繁体   English   中英

如何从递归方法返回布尔值?

[英]How do i return boolean from recursive method?

此方法在给定的迷宫中找到从左上角到右下角的路径。 我已经检查过,我的方法找到了一条路径,但是完成后我无法让它返回true。 它从我的if语句中打印出“您成功做到了”,但是它返回true。

if((x0 == x1) && (y0 == y1)) {
        System.out.println(l);
        System.out.println("You made it");
        return true;
    }

我知道这是递归的,并且您以不同的方式返回值。 我仍然不知道如何正确返回我的值。

继承方法:

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;
}

}

您需要传播return语句。 不仅仅是调用findPath(x0+1, y0, x1, y1, l); 递归地,您需要执行以下操作:

return findPath(x0+1, y0, x1, y1, l);

此外,这样一来,您就可以消除所有的“ else”语句。 只要是就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM