kalombo
kalombo

Reputation: 871

How can i get directed tree from graph?

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?

Upvotes: 7

Views: 8849

Answers (2)

Aric
Aric

Reputation: 25289

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)

Upvotes: 3

unutbu
unutbu

Reputation: 879093

To get the directed tree of breadth-first-search from node 4:

tree = nx.bfs_tree(G, 4)

enter image description here


To get the directed tree of depfth-first search from node 4:

tree = nx.dfs_tree(G, 4)

enter image description here


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')

Upvotes: 14

Related Questions