Spanning tree of directed graph with networkx

偶尔善良 提交于 2020-04-11 03:10:45

问题


I have a directed graph G in networkx and I want to get the minimum spanning tree of it. I do:

 T = nx.algorithms.minimum_spanning_tree( G.to_undirected()  )

This is undirected and I would like to restore the directions but I don't know how to do it. I tried:

G[T.edges()]

This last line looks very pythonic but this is not the way networkx works, apparently... Does anyone knows how to do it?

In other words: How can I get the subgraph of a directed tree given the (undirected) edges ?


回答1:


You can get the edges in G that appear in the MST T with a simple comprehension:

E = set(T.edges())  # optimization
[e for e in G.edges() if e in E or reversed(e) in E]

You can then build a new graph from this.



来源:https://stackoverflow.com/questions/23537137/spanning-tree-of-directed-graph-with-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!