I’m trying to find a path between two points on a map.
When it breaks out from the loop and returns the weight, it goes to the else statement and calls find again. Why does the code do this?
public int find() throws LinkException {
Node currentNode = map.getNode(origin);
int weight = 0;
return find(currentNode, null, weight);
}
private int find(Node currentNode, Node pastNode, int weight) throws LinkException {
for (Node futureNode : currentNode.getLinks()) {
if (currentNode == futureNode || futureNode == pastNode) {
continue;
}
weight += currentNode.getLink(futureNode).getWeight();
pastNode = currentNode;
currentNode = futureNode;
if (currentNode.getName().equals(destination)) { // Here we reach the destination
break;
} else {
find(currentNode, pastNode, weight);
}
}
return weight;
}
That’s how recursion works. You have multiple nested calls to
find()happening at the same time. When the innermost call finishes, the next-innermost resumes its operation and proceeds to the next operation of itsforloop.By the way, you are ignoring the return value of the recursive call to
find(). That doesn’t look right.