简体   繁体   中英

How to treat a `networkx.digraph` as un-directed

I have a directed graph G represented as a networkx.digraph . I want to be able to do shortest-path computations on the undirected version of that graph. How do I get an object that is the undirected version of that graph.

I know it will involve making a graph view , however the documentation for generic_graph_view is not very useful in explaining how to achieve this; nor is the code itself for some one that is not familiar with the internals of the library.

You can just pass your directed graph to nx.Graph

G=nx.fast_gnp_random_graph(10,.2,directed=True)
G_undirected = nx.Graph(G)

print(G.edges)
# OutEdgeView([(0, 1), (0, 5), (1, 0), (1, 2), (1, 6), (1, 9),
# (2, 7), (2, 9), (3, 4), (4, 7), (5, 4), (6, 0), (7, 8),
# (8, 9), (9, 4)])

print(G_undirected.edges)
# EdgeView([(0, 1), (0, 5), (0, 6), (1, 2), (1, 6), (1, 9), (2, 7),
# (2, 9), (3, 4), (4, 7), (4, 5), (4, 9), (7, 8), (8, 9)])

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