在图中查找所有可能的路径

coj*_*joj 5 algorithm traversal graph-theory breadth-first-search depth-first-search

我正在寻找一些算法来帮助我在图中找到所有可能的路径。到目前为止我发现的一切都不完全令人满意。

假设我们有一个像这样的图(树):
在此处输入图片说明

让我们使用一些算法,如广度优先搜索深度优先搜索。作为回报,我们会得到类似的东西

1, 2, 4, (2), 5, (2), 6, (2), (1), 3, 7, 8, (7), 9
Run Code Online (Sandbox Code Playgroud)

这就是我们通过这棵树的方式,这不是我要找的。我很想获得所有路径,例如:

1
1, 2
1, 2, 4
1, 2, 5
1, 2, 6
1, 3
1, 3, 7
1, 3, 7, 8
1, 3, 7, 9
Run Code Online (Sandbox Code Playgroud)

问题是我只想指定root节点和算法应该能够为我提供任何长度的所有可能路径。


到目前为止,我拥有的简单代码如下所示:

func dfs(_ graph: Graph, source: Node) -> [String] {
    var nodesExplored = [source.label]
    source.visited = true

    for edge in source.neighbors {
        if !edge.neighbor.visited {
            nodesExplored += dfs(graph, source: edge.neighbor)
        }
    }

    return nodesExplored
}
Run Code Online (Sandbox Code Playgroud)

jrb*_*ard 0

您可以在二叉树上使用此算法来打印其所有根到叶路径。该函数treePaths以深度优先 (DFS)、预序、递归方式遍历节点。

treePaths(root, path[1000], 0) // initial call, 1000 is a path length limit

// treePaths traverses nodes of tree DFS, pre-order, recursively
treePaths(node, path[], pathLen)
    1) If node is not NULL then 
        a) push data to path array: 
            path[pathLen] = node->data.
        b) increment pathLen 
            pathLen++
    2) If node is a leaf node, then print the path array, from 0 to pathLen-1
    3) Else
        a) Call treePaths for left subtree
            treePaths(node->left, path, pathLen)
        b) Call treePaths for right subtree.
            treePaths(node->right, path, pathLen)
Run Code Online (Sandbox Code Playgroud)