在图

时间:2016-12-20 18:23:44

标签: algorithm graph-theory traversal depth-first-search breadth-first-search

我正在寻找一些算法,它可以帮助我在图表中找到所有可能的路径。到目前为止我发现的一切都不是完全满足。

让我们想象我们有一个像这样的图(树):
enter image description here

让我们使用一些算法,例如广度优先搜索深度优先搜索。作为回报,我们会得到像

这样的东西
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 :(得分: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)

答案 1 :(得分: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
相关问题