floyd_warshall#
- floyd_warshall(G, weight='weight')[source]#
Find all-pairs shortest path lengths using Floyd’s algorithm.
- Parameters:
- GNetworkX graph
- weightstring or function (default= ‘weight’)
If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining
utovwill beG.edges[u, v][weight]). If no such edge attribute exists, the weight of the edge is assumed to be one.If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge.
- Returns:
- distancedict
A dictionary, keyed by source and target, of shortest paths distances between nodes.
See also
floyd_warshall_predecessor_and_distancefloyd_warshall_numpyall_pairs_shortest_pathall_pairs_shortest_path_length
Notes
Floyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time \(O(n^3)\) with running space of \(O(n^2)\).
Examples
>>> from pprint import pprint >>> G = nx.DiGraph() >>> G.add_weighted_edges_from( ... [(0, 1, 5), (1, 2, 2), (2, 3, -3), (1, 3, 10), (3, 2, 8)] ... ) >>> fw = nx.floyd_warshall(G, weight="weight") >>> results = {a: dict(b) for a, b in fw.items()} >>> pprint(results) {0: {0: 0, 1: 5, 2: 7, 3: 4}, 1: {0: inf, 1: 0, 2: 2, 3: -1}, 2: {0: inf, 1: inf, 2: 0, 3: -3}, 3: {0: inf, 1: inf, 2: 8, 3: 0}} ----
Additional backends implement this function
graphblas : OpenMP-enabled sparse linear algebra backend.