Take the 2-minute tour ×

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) {
        weight += currentNode.getLink(futureNode).getWeight();
        pastNode = currentNode;
        currentNode = futureNode;
        if (currentNode.getName().equals(destination)) { // Here we reach the destination
        } else {
            find(currentNode, pastNode, weight);
     return weight;
share|improve this question
Use the debugger to follow the flow of your program. –  user714965 Nov 28 '12 at 9:22
just debug it to see what happens exactly... also, insteadof breaking you could just return weight –  moeTi Nov 28 '12 at 9:22
I observed this behaviour while debugging. When return statement is reached it goes back to the else branch and calls itself again. –  locke Nov 28 '12 at 9:24
Quite apart from understanding why this is happening, you should probably change the way your program works: as it is, it is likely that it will loop infinitely on three nodes in a triangle without finding the solution. You should check known algorithms: en.wikipedia.org/wiki/Dijkstra's_algorithm –  user711413 Nov 28 '12 at 9:33
add comment

1 Answer

up vote 2 down vote accepted

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 its for loop.

By the way, you are ignoring the return value of the recursive call to find(). That doesn't look right.

share|improve this answer
So I need a flag it exit from all calls? –  locke Nov 28 '12 at 9:29
@locke: That depends on the logic you're trying to implement. –  NPE Nov 28 '12 at 9:30
add comment

Your Answer


