networkx是否支持按标签遍历dfs

时间:2013-05-15 20:45:04

标签: python graph networkx depth-first-search dfs

networkx dfs_edges()函数将迭代子节点。据我所知,http://networkx.lanl.gov/文档没有在dfs_edges()中指定一个参数,只有在边有特定标签时才会遍历。

另外,我查看了dfs_labeled_edges(),但只是在用DFS迭代图时告诉你遍历方向。

2 个答案:

答案 0 :(得分:4)

没有选项只能遍历具有给定标签的边。如果您不介意制作图表副本,则可以构建一个新图表,其中只包含您想要的特定标签的边缘。

如果这不起作用,那么修改dfs_edges()的源代码就不那么难了。 e.g。

if source is None:
    # produce edges for all components
    nodes=G
else:
    # produce edges for components with source
    nodes=[source]
visited=set()
for start in nodes:
    if start in visited:
        continue
    visited.add(start)
    stack = [(start,iter(G[start]))] <- edit here
    while stack:
        parent,children = stack[-1]
        try:
            child = next(children)
            if child not in visited:
                yield parent,child
                visited.add(child)
                stack.append((child,iter(G[child]))) <- and edit here
        except StopIteration:
            stack.pop()

答案 1 :(得分:0)

我有一种适合我的方法。感谢@Aric的灵感。

它位于https://github.com/namoopsoo/networkx/blob/master/networkx/algorithms/traversal/depth_first_search.py

这是一个名为dfs_edges_by_label()的新函数。并且将标签作为输入,它仅遍历与标签匹配的边缘。