Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
kalombo Avatar asked Mar 14 '13 07:03

kalombo


2 Answers

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')
like image 160
unutbu Avatar answered Sep 20 '22 22:09

unutbu


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)
like image 44
Aric Avatar answered Sep 21 '22 22:09

Aric