user1427661
user1427661

Reputation: 11774

Understanding This Depth First Search Algorithm

I have been given a DFS algorithm that returns the shortest path to a goal node. It takes as arguments a graph (with all of the nodes and their paths), a starting node, a goal node, and a list of nodes that have been visited (initialized as empty). Here is the code:

def shortestPath(graph, start, end, visited = []):
    path = str(start)
    if start == end:
        return path
    shortest = None
    for node in graph.childrenOf(start):
        if str(node) not in visited:
            visited = visited + [str(node)]
            newPath = shortestPath(graph, start, end, visited)
            if newPath = None:
                continue
            if shortest == None or len(newPath) < shortest:
                shortest = newPath
    if shortest != None:
         path = path + shortest
    else:
         path = None
    return path

I understand the concept of Depth First Search, but this recursion is boggling my mind. Let me know if my train of thought is at all on track and where I'm getting derailed.

So basically, the recursion occurs when newPath is assigned a value, which of course is a call to shortestPath. At that point, the recursion goes all the way down the graph until it either reaches a node with no children or the goal node. If it reaches a node with no children that isn't the goal, the base case is ignored, and the entire for loop is ignored, returning a value of none. That None then is simply passed up the chain of recursion. If it reaches the goal node, then the bottom layer of the recursion actually returns a value (path), which bubbles up to the top of the recursion.

At that point I get confused, because of what is going on with "shortest." So every time an actual value is returned for newPath, shortest is assigned that value, but then it is added to path. But let's say I have multiple paths to the goal node. I successfully find the first path, and path is equal to the sum of all of the newPaths/shortests. But then for the next recursion that successfully reaches the goal, doesn't path just keep adding on more newPaths? So won't the final result be a long list of every path I COULD visit to reach the goal node instead of the shortest path?

Upvotes: 3

Views: 2491

Answers (1)

Petar Minchev
Petar Minchev

Reputation: 47363

The path variable is local to the function. Every recursion call has its own stack frame - it is independent from the other calls). That means when the next call starts, then everything is brand new.

Upvotes: 3

Related Questions