import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,5)
G.add_edge(4,6)
G.add_edge(1,6)
G.add_edge(2,6)
G.add_edge(7,8)
G.add_edge(9,8)
mst=nx.prim_mst(G)# a generator of MST edges
I have got a tree. How can i get directed tree with root at 4?
To get the directed tree of breadth-first-search from node 4:
tree = nx.bfs_tree(G, 4)
To get the directed tree of depfth-first search from node 4:
tree = nx.dfs_tree(G, 4)
The graphs were generated this way:
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,5)
G.add_edge(4,6)
G.add_edge(1,6)
G.add_edge(2,6)
G.add_edge(7,8)
G.add_edge(9,8)
tree = nx.bfs_tree(G, 4)
nx.draw(tree)
plt.savefig('/tmp/bfs_image.png')
It might be that @kalombo wants an oriented tree from the MST of G with root at node 4. In that case you will need to build the graph of the MST first. e.g.
T = nx.bfs_tree(nx.Graph(nx.prim_mst_edges(G)),4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With