What is a Graph? · Definitions
Lesson 11
This is how you can find it using built-in Python methods.
from networkx import Graph, shortest_path, shortest_path_length
g = Graph()
for u, v, w in [
('A', 'B', 3), ('A', 'F', 4), ('B', 'G', 1), ('F', 'G', 3),
('B', 'C', 4), ('C', 'G', 2), ('F', 'E', 8), ('G', 'E', 7),
('C', 'D', 5), ('E', 'D', 2), ('C', 'E', 1)
]:
g.add_edge(u, v, weight=w)
print(shortest_path_length(g, source='A', target='D', weight='weight'))
print(shortest_path(g, source='A', target='D', weight='weight'))9
['A', 'B', 'G', 'C', 'E', 'D']