简体   繁体   中英

iterating over nodes of a NetworkX DiGraph in-order

Is there a way to iterate over the nodes of a NetworkX DiGraph in order? The traversal methods I found iterate over edges rather than nodes, or require a source. In my case, my DAG has multiple sources. I don't really care in which order these sources are iterated over, as long as one node does not get processed before all of its ancestors have been processed.

I usually implement something like this:

import networkx as nx

G = nx.gnr_graph(100, 0.1)

root_node = list(G.nodes)[80]

children_next = set()
searched_nodes = set()
children_current = [root_node]

level = 0
while len(children_current) != 0:


    for n in children_current:
        searched_nodes.add(n)

        for s in G.successors(n): #exchange with predecessors to get parents
            children_next.add(s)

        children_next = children_next.difference(searched_nodes)

    children_current = list(children_next)

    level += 1

    print("root={}; level={}, successors={}".format(root_node, level, str(children_current)))

This allows me to travers the graph in a direction (exchange G.successors(n) with G.predecessors(n) to change the direction). It traverses the nodes of the graph according to their distance from the root node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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