networkx是否跟踪节点深度?

13

有人知道 python networkx 是否为使用 Networkx DiGraph 创建的树预先计算节点深度吗?

由于我没有看到在 networkx 中定义树的方法,也许需要使用外部数据结构来计算节点深度。

1个回答

12

如果您知道树的根节点,可以使用 shortest_path() 函数来获取从根节点到目标节点的距离:

In [1]: import networkx as nx

In [2]: G = nx.DiGraph()

In [3]: G.add_path([0,10,20,30])

In [4]: G.add_path([0,1,2,3])

In [5]: nx.shortest_path_length(G,0) # assume a tree rooted at node 0
Out[5]: {0: 0, 1: 1, 2: 2, 3: 3, 10: 1, 20: 2, 30: 3}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接