This is a snippet of a code that works as a pathfinder, and it uses a recursive method. I don't quite see how it works though. So, we let the user create the labyrinth, and after he did, we start the method findRek in the main method. We check whether some field is a wall or a path that we already walked on (marked by a " - "). We want to mark every field that is not the start but is still free.
In the second paragraph, we work with the principle of recursion, checking top, down, left and right - that's were I'm lost. So the method is calling itself here, but under what circumstances does it return a "true"? Only when the field that we stand on is the goal? Plus, what happens here if we get a "false" after calling the method again with a certain direction? Does it check every direction then?
The last paragraph in the recursive method sets the field we are standing on as free since it was marked as a path before, which would always lead to a false.
private static boolean findRek(char[][] lab, int x, int y) {
if (lab [y][x] == GOAL)
return true;
if (lab [y][x] == WALL)
return false;
if (lab [y][x] == PATH)
return false;
if (lab [y][x] != START)
lab[y][x] = PATH;
if (findRek(lab, x, y-1))
return true;
if (findRek(lab, x+1, y))
return true;
if (findRek(lab, x, y+1))
return true;
if (findRek(lab, x-1, y))
return true;
lab[y][x] = FREE;
return false;
}
...
public static void main(String[]args) {
boolean yes = findRek(lab);
if(yes) {
...
Since this was called a possible duplicate: It's not like I didn't understand recursion in genereal, but I don't quite get the operating principle of the boolean variables here.