networkx.algorithms.single_source_bellman_ford

networkx.algorithms.single_source_bellman_ford(G, source, target=None, cutoff=None, weight='weight')[source]

Compute shortest paths and lengths in a weighted graph G.

Uses Bellman-Ford algorithm for shortest paths.

Parameters:

G : NetworkX graph

source : node label

Starting node for path

target : node label, optional

Ending node for path

cutoff : integer or float, optional

Depth to stop the search. Only paths of length <= cutoff are returned.

Returns:

distance,path : dictionaries

Returns a tuple of two dictionaries keyed by node. The first dictionary stores distance from the source. The second stores the path from the source to that node.

Notes

Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.

Examples

>>> G=nx.path_graph(5)
>>> length,path=nx.single_source_bellman_ford(G,0)
>>> print(length[4])
4
>>> print(length)
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
>>> path[4]
[0, 1, 2, 3, 4]