代码之家  ›  专栏  ›  技术社区  ›  Tyler

有向非循环图中从源到接收器的所有路径的列表[重复]

  •  5
  • Tyler  · 技术社区  · 16 年前

    可能重复:
    [python]: path between two nodes

    有人能告诉我一些有关如何做到这一点的资源吗?我在用 networkx 作为我的python库。

    谢谢!

    3 回复  |  直到 15 年前
        1
  •  6
  •   Boris Gorelik    15 年前

    这是基于亚历克斯·马泰利的回答,但它应该起作用。这取决于表达式 source_node.children 生成一个iterable,该iterable将遍历 source_node . 它还依赖于 == 运算符比较两个节点以查看它们是否相同。使用 is 可能是更好的选择。显然,在您使用的库中,让所有的孩子都可以阅读的语法是 graph[source_node] ,因此需要相应地调整代码。

    def allpaths(source_node, sink_node):
        if source_node == sink_node: # Handle trivial case
            return frozenset([(source_node,)])
        else:
            result = set()
            for new_source in source_node.children:
                paths = allpaths(new_source, sink_node, memo_dict)
                for path in paths:
                    path = (source_node,) + path
                    result.add(path)
            result = frozenset(result)
            return result
    

    我主要关心的是,这是一个深度优先搜索,当有几个路径从源到一个节点是孙子、曾孙等所有的源,但不一定是一个接收器的父节点时,这将浪费精力。如果它为给定的源节点和接收节点记住了答案,就可以避免额外的工作。

    下面是一个如何工作的例子:

    def allpaths(source_node, sink_node, memo_dict = None):
        if memo_dict is None:
            # putting {}, or any other mutable object
            # as the default argument is wrong 
            memo_dict = dict()
    
        if source_node == sink_node: # Don't memoize trivial case
            return frozenset([(source_node,)])
        else:
            pair = (source_node, sink_node)
            if pair in memo_dict: # Is answer memoized already?
                return memo_dict[pair]
            else:
                result = set()
                for new_source in source_node.children:
                    paths = allpaths(new_source, sink_node, memo_dict)
                    for path in paths:
                        path = (source_node,) + path
                        result.add(path)
                result = frozenset(result)
                # Memoize answer
                memo_dict[(source_node, sink_node)] = result
                return result
    

    这还允许您在调用之间保存memoization字典,因此如果需要计算多个源节点和接收节点的答案,可以避免大量额外的工作。

        2
  •  2
  •   bukzor    15 年前

    这一个实际上与networkx一起工作,并且它是非递归的,对于大型图形来说可能很好。

    def find_all_paths(graph, start, end):
        path  = []
        paths = []
        queue = [(start, end, path)]
        while queue:
            start, end, path = queue.pop()
            print 'PATH', path
    
            path = path + [start]
            if start == end:
                paths.append(path)
            for node in set(graph[start]).difference(path):
                queue.append((node, end, path))
        return paths
    
        3
  •  1
  •   Alex Martelli    16 年前

    我不确定是否有特殊的优化可用——在寻找它们之前,我会做一个简单的递归解决方案,比如(使用networkx,只使用一个节点为一个图编制索引的功能,它提供了一个可生成其相邻节点的iterable(在networkx的情况下是一个dict,但我并没有特别使用它):……

    def allpaths(G, source_nodes, set_of_sink_nodes, path_prefix=()):
      set_of_result_paths = set()
      for n in source_nodes:
        next_from_n = []
        for an in G[n]:
          if an in set_of_sink_nodes:
            set_of_result_paths.add(path_prefix + (n, an))
          else:
            next_from_n.append(an)
        if next_from_n:
          set_of_result_paths.update(
              allpaths(G, next_from_n, set_of_sink_nodes, path_prefix + (n,)))
      return set_of_result_paths
    

    这应该是可以证明的正确的(但我不会做这个证明,因为它已经很晚了,而且我头昏眼花;-)并且可以用来验证任何进一步的优化;-。

    我尝试的第一个优化是某种简单的记忆化:如果我已经计算了从某个节点n到任何目标节点的路径集(无论我进行计算时指向n的前缀是什么),我可以将其存储在n键下的dict中,并避免在我通过不同的路径再次到达n时进行进一步的重新计算;—)。