Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this python code employs Depth First Search (DFS) for finding all paths?

This code is given in python official essays on graph theory. Here's the code:

def find_all_paths(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return [path]
        if not graph.has_key(start):
            return []
        paths = []
        for node in graph[start]:
            if node not in path:
                newpaths = find_all_paths(graph, node, end, path)
                for newpath in newpaths:
                    paths.append(newpath)
        return paths

I am not adept at python as I haven't yet had enough of practicing and reading in it. Can you please explain the code by relating this to the child-sibling concept in DFS diagram? Thanks.


1 Answers

The key to seeing that it is a DFS is that the recursion happens before the accumulation of paths. In other words the recursion will go as deep as it needs to go before putting anything on the "paths" list. All the deepest siblings are accumulated on "paths" before returning the list.

I believe the code is correct with the "append" rather than "extend", since "paths" is the accumulator of all paths. Though it could probably be written as

paths += find_all_paths(graph, node, end, path)

(edit) ...instead of

 newpaths = find_all_paths(graph, node, end, path)
 for newpath in newpaths:
     paths.append(newpath)
like image 65
mjhm Avatar answered Mar 04 '26 12:03

mjhm