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. It prints out "You made it" from my if-statement, but it dosent returns 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. Instead of just calling 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. Just the if's will suffice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.