Shortest path

shortest_path unweighted.

shortest_path is unweighted (hops). Weighted roads wait for Dijkstra.

Goal

Print Nairobi→Kisumu hop path.

import networkx as nx
G = nx.Graph()
G.add_edges_from([('Nairobi', 'Nakuru'), ('Nakuru', 'Kisumu'), ('Nairobi', 'Mombasa'), ('Mombasa', 'Kisumu')])
print(nx.shortest_path(G, 'Nairobi', 'Kisumu'))
print(nx.shortest_path_length(G, 'Nairobi', 'Kisumu'))
import networkx as nx
G = nx.path_graph(['a', 'b', 'c', 'd'])
print(nx.all_simple_paths(G, 'a', 'd'))
print(list(nx.all_simple_paths(G, 'a', 'd')))
import networkx as nx
G = nx.Graph([('Nairobi', 'Nakuru')])
try:
    nx.shortest_path(G, 'Nairobi', 'Kisumu')
except nx.NetworkXNoPath as err:
    print(type(err).__name__)
import networkx as nx
print(nx.shortest_path(nx.complete_graph(4), 0, 3))