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

后端 未结 3 1847
执笔经年
执笔经年 2021-01-15 02:20

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]         


        
3条回答
  •  轮回少年
    2021-01-15 03:03

    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)
    

提交回复
热议问题