Camins¶
Importem la biblioteca networkx.
>>> import networkx as nx
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])
Visualitzem el graf utilitzant matplotlib/pyplot.
>>> import matplotlib.pyplot as plt
>>> pos = nx.nx_agraph.graphviz_layout(g)
>>> nx.draw_networkx(g, pos)
>>> plt.show()
Consultem si hi ha camí entre 1 i 4.
>>> nx.has_path(g, 1, 4)
True
Consultem tots els camins simples entre 1 i 4.
>>> for c in sorted(nx.all_simple_paths(g, 1, 4)):
... print(c)
[1, 2, 4]
[1, 3, 4]
[1, 5, 3, 4]
Consultem la longitud del camí mínim. És única.
>>> nx.shortest_path_length(g, 1, 4)
2
Consultem un camí mínim. No és únic.
>>> nx.shortest_path(g, 1, 4)
[1, 2, 4]
Consultem tots els camins mínims.
>>> for c in sorted(nx.all_shortest_paths(g, 1, 4)):
... print(c)
[1, 2, 4]
[1, 3, 4]
Afegim un atribut distància a les arestes.
>>> g[1][2]['dist'] = 3
>>> g[1][3]['dist'] = 4
>>> g[1][5]['dist'] = 1
>>> g.edges[2, 4]['dist'] = 5
>>> g.edges[3, 4]['dist'] = 2
>>> g.edges[3, 5]['dist'] = 1
Visualitzem el graf amb l’etiqueta dist a les arestes.
>>> edge_labels = {(u, v): f"{data}" for u, v, data in g.edges(data='dist')}
>>> nx.draw_networkx(g, pos)
>>> r = nx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels)
>>> plt.show()
Consultem la longitud del camí mínim segons l’etiqueta dist.
>>> nx.shortest_path_length(g, 1, 4, weight='dist')
4
Consultem un camí mínim.
>>> nx.shortest_path(g, 1, 4, weight='dist')
[1, 5, 3, 4]
Afegim un altre camí.
>>> nx.add_path(g, [6, 7])
Hi ha camí entre 1 i 6?.
>>> nx.has_path(g, 1, 6)
False