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_wof 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 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:
- 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']