识别源节点在NetworkX DiGraph中具有两个邻居之后的第一个节点

时间:2016-02-08 13:31:28

标签: python networkx

我正在使用NetworkX实现DiGraph。源是红色节点。我需要识别从具有两个邻居的红色节点开始的第一个节点(在“流向”中)。如果我遍历所有节点 - 它似乎是ramdom。如果有人可以帮忙的话会很棒!

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用successors方法。如果您的DiGraph实例名为G,并且您的红色节点的索引为0,那么您可以采用breadth first search方式:

import networkx as nx

# Construct graph from example image, all edges pointing away from source
G = nx.DiGraph()
G.add_path([0,1,2,3,4])
G.add_path([1,5])
G.add_path([3,6])
G.add_path([2,7,8])

# Find first with 2 neighbors
neighbors = G.successors(0)
for n in neighbors:
    nneighbors = set(G.successors(n))
    if len(nneighbors) == 2:
        print "Found", n
        break
    neighbors.extend(nneighbors)

对于网络x中的DiGraph,neighbors方法可与successors互换。如果您还要计算每个节点的输入边缘数,请在计算时将G.predecessors(n)添加到nneighbors集,但请记住在扩展neighbors时不要将它们包含在集合中。那么代码就是:

# Find first with 2 neighbors
neighbors = G.successors(0)
for n in neighbors:
    if len(G.predecessors(n)+G.successors(n)) == 2:
        print "Found", n
        break
    nneighbors = set(G.successors(n))
    neighbors.extend(nneighbors)