floyd_warshall_tree#

floyd_warshall_tree(G, weight='weight')[source]#

Find all-pairs shortest path lengths using a Tree-based modification of Floyd’s algorithm.

This variant implements the Tree algorithm of Brodnik, Grgurovic and Pozar. It differs from the classical Floyd Warshall algorithm by using a shortest path tree rooted at each intermediate vertex w. For every w, the algorithm builds a tree OUT_w of shortest paths for the current iteration and scans the tree in depth first order. If an update at a vertex v cannot improve any distance, the algorithm skips the entire subtree below v, since none of its nodes can produce a shorter path, as proved in [1].

Parameters:
GNetworkX graph
weightstring, optional (default= ‘weight’)

Edge data key corresponding to the edge weight.

Returns:
predecessor, distancedict and dict-of-dict

Predecessor is a dict keyed by node to the predecessor node in the shortest path. The distance output is a dict keyed by source node to a dict keyed by target node to the distance value of the shortest path between the source and target.

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 worst case running time \(O(|V|^3)\) with running space of \(O(|V|^2)\).

For complete directed graphs with independent edge weights drawn from the uniform distribution on [0, 1], the expected running time is \(O(|V|^2 (\log |V|)^2)\), as shown in [1].

References

[1] (1,2)

Brodnik, Andrej, Marko Grgurovic, and Rok Pozar. “Modifications of the Floyd-Warshall algorithm with nearly quadratic expected-time.” Ars Math. Contemp. 22, no. 1 (2022). https://doi.org/10.26493/1855-3974.2467.497

Examples

>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
...     [
...         ("s", "u", 10),
...         ("s", "x", 5),
...         ("u", "v", 1),
...         ("u", "x", 2),
...         ("v", "y", 1),
...         ("x", "u", 3),
...         ("x", "v", 5),
...         ("x", "y", 2),
...         ("y", "s", 7),
...         ("y", "v", 6),
...     ]
... )
>>> predecessors, distances = nx.floyd_warshall_tree(G)
>>> nx.reconstruct_path("s", "v", predecessors)
['s', 'x', 'u', 'v']