Recorreguts¶
Importem la biblioteca networkx i el mòdul
pyplot de la biblioteca matplotlib.
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
Creem un graf buit.
>>> g = nx.Graph()
Hi afegim dos camins.
>>> nx.add_path(g, [1, 2, 4, 3, 1])
>>> nx.add_path(g, [1, 5, 3])
Hi afegim un altre camí.
>>> nx.add_path(g, [6, 7])
Hi afegim un vèrtex.
>>> g.add_node(8)
Visualitzem el graf.
>>> pos = nx.nx_agraph.graphviz_layout(g)
>>> nx.draw(g, pos, with_labels=True)
>>> plt.show()
Recorregut en profunditat a partir de 2.
>>> t = nx.dfs_tree(g, 2)
Visualitzem l’arbre del recorregut.
>>> nx.draw(t, pos, with_labels=True)
>>> plt.show()
Recorregut en amplada a partir de 2.
>>> t = nx.bfs_tree(g, 2)
Visualitzem l’arbre del recorregut.
>>> nx.draw(t, pos, with_labels=True)
>>> plt.show()