简体   繁体   English

这种深度优先搜索变体是否有特定名称?

[英]Is there a specific name for this depth-first-search variant?

I use the algorithm below to traverse a (networkx) graph in a specific order.我使用下面的算法以特定顺序遍历(networkx)图。 It is similar to a classic depth-first search with the difference that the deeper nodes are retrieved before their parent nodes.它类似于经典的深度优先搜索,不同之处在于较深的节点在其父节点之前检索。 Out of curiosity: would there be any specific name to refer to this behaviour?出于好奇:是否有任何具体的名称来指代这种行为?

>>> import networkx

>>> def traverse_graph_dfs_like(graph, source):
...     """Yield nodes from graph beginning with the lowest left"""

...     stack = []
...     stack.append(source)
...     child_generators = {source: graph.neighbors(source)}

...     while stack:
...         try:
...             first_child = next(child_generators[stack[-1]])
...         except StopIteration:
...             yield stack.pop()
...         else:
...             stack.append(first_child)
...             child_generators[first_child] =  graph.neighbors(first_child)

>>> g = networkx.DiGraph({0: [1, 2], 1: [3, 4], 2: [5, 6]})

>>> list(traverse_graph_dfs_like(g, 0))
[3, 4, 1, 5, 6, 2, 0]


>>> list(networkx.algorithms.dfs_tree(g, 0))
[0, 1, 3, 4, 2, 5, 6]

You want to visit nodes with depth-first-search post-order .您想使用 depth-first-search post-order访问节点。 In this method, you traverse subtrees from left to right by recursively calling the post-order function.在此方法中,您通过递归调用后序 function 从左到右遍历子树。 Once you have traversed them all, you access the data part of the current node.一旦你遍历了它们,你就可以访问当前节点的数据部分。 There are other ways to traverse a tree (for example, pre-order , in-order , reverse in-order , etc.).还有其他遍历树的方法(例如pre-orderin-orderreverse in-order等)。 For more info you can refer to this Wikipedia page.有关更多信息,您可以参考Wikipedia 页面。

NetworkX does provide an implementation of this algorithm: networkx.algorithms.traversal.depth_first_search.dfs_postorder_nodes . NetworkX 确实提供了这个算法的实现: networkx.algorithms.traversal.depth_first_search.dfs_postorder_nodes Specifically, it is a generator of nodes in a depth-first-search pre-ordering.具体来说,它是深度优先搜索预排序中的节点生成器。 Here's how you can use it:以下是您可以使用它的方法:

from networkx import DiGraph
from networkx.algorithms.traversal.depth_first_search import dfs_postorder_nodes

g = DiGraph({0: [1, 2], 1: [3, 4], 2: [5, 6]})
print(*dfs_postorder_nodes(g, source=0))

The printed output is exactly what you are looking for: 3 4 1 5 6 2 0 .印刷的 output 正是您要找的: 3 4 1 5 6 2 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM