且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从起始节点查找DAG中的所有路径

更新时间:2023-01-26 07:59:28

您要尝试创建的实际上是从 BFS DFS 遍历 DAG .您可以通过稍微更改代码来做到这一点.

what you are trying to create is actually the tree created from BFS or DFS traversal over a DAG. You can do this by changing your code a bit.

首先请注意,您有一些不必要的代码部分:

First of all notice that you have some unnecessary code parts:

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

由于我们假设这是DAG,所以我们可以摆脱一些条件...

Since we assume this is a DAG we can get rid of some conditions...

现在,我们要生成DFS遍历的路径.此处的打印将在每次迭代后打印一条路径,但是我们想在结束时打印该路径.
因此,我们将添加一个简单的if语句来检查这是否是路径的结尾,如果是,我们将打印路径:

Now we want to generate the paths of a DFS traversal. The print here will print a path after each iteration but we would like to print the path after we reached an end.
So we will add a simple if statement to check if this is the end of the path and if it is we will print the path:

def find_all_paths(graph, start, path=[]):
    path = path + [start]
    paths = [path]
    if len(graph[start]) == 0:  # No neighbors
        print(path)
    for node in graph[start]:
        newpaths = find_all_paths(graph, node, path)
        for newpath in newpaths:
            paths.append(newpath)
    return paths

结果:

[6, 7]
[6, 15, 16, 21]
[6, 15, 9, 13, 4, 1, 5]