首页 文章

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

提问于
浏览
4

我正在寻找一些 algorithm ,这将帮助我在图表中找到 all possible 路径 . 到目前为止我发现的一切并不完全令人满意 .

让我们假设我们有一个像这样的图形(树):

enter image description here

让我们使用像 Breadth-First SearchDepth-First Search 这样的算法 . 作为回报,我们会得到类似的东西

1, 2, 4, (2), 5, (2), 6, (2), (1), 3, 7, 8, (7), 9

这是我们如何通过这棵树,这不是我喜欢的所有路径,如:

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

问题是我只想指定 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
}

2 回答

  • 0

    只需折叠结果并计算新的可能性:结果= 9(您忘记了路径[1])

    n0  n1  n2  n3
    1,   2,  4,       +3
        (2), 5,       +1
        (2), 6,       +1
        (2),          +0
    (1), 3,  7,  8,   +3
            (7), 9    +1
    
  • 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)
    

相关问题