Shortest paths

Shortest paths

The cheapest route from one vertex to another, with weights that are exact fractions. Ties are real ties, and when a negative cycle makes the question meaningless, the cycle is what you get back.

One route

const g = graph("s-a:0.1 a-b:0.2 b-t:0.3 s-t:0.6");
shortestPath(g, "s", "t");
// { distance: 3/5, path: ["s", "t"], edges: [ … ] }: the other route is also 3/5
shortestPath(g, "s", "b").distance.toString();    // "3/10"

In floating point, 0.1 + 0.2 + 0.3 is 0.6000000000000001, so the route through a and b would look slightly longer than the direct edge of weight 0.6. Here weights and distances are Core Rationals, so the two routes are recognised as exactly equal: both are 3/5, and either is a correct answer. A weight may be written as a whole number, a fraction "3/7" or a decimal string "0.1"; a JavaScript non-integer such as 0.1 is refused, because the number it stands for is not one tenth.

From one vertex to all others

const d = digraph("A>B:4 A>C:2 C>B:1 B>D:5 C>D:8 D>E:3");
const sp = shortestPaths(d, "A");
sp.method;                         // "dijkstra"
[...sp.distance].map(([v, x]) => `${{v}}:${{x}}`);   // ["A:0", "B:3", "C:2", "D:8", "E:11"]
sp.pathTo("E").path;               // ["A", "C", "B", "D", "E"]

Dijkstra's method settles vertices in order of distance. It keeps the best distance found so far for each vertex, repeatedly settles the unsettled vertex with the smallest one, and tries the edges out of it. When no weight is negative, a settled vertex can never be improved later: any other route to it passes through some unsettled vertex that is already at least as far. With a binary heap this takes time about (∣V∣+∣E∣)log⁡∣V∣(|V| + |E|) \log |V| comparisons of fractions.

When every weight is 1 (an unweighted graph), breadth-first search does the same job, and method says so.

Negative weights, and negative cycles

const d = digraph("s>a:4 s>b:2 b>a:-3 a>t:1");
shortestPath(d, "s", "t").distance.toString();    // "0": via b, then back to a
shortestPaths(d, "s").method;                     // "bellman-ford"

const loop = digraph("s>a:1 a>b:-2 b>a:1 b>t:1");
shortestPaths(loop, "s").negativeCycle;           // ["a", "b", "a"]
shortestPath(loop, "s", "t");                     // throws: the cycle a → b → a has negative total weight

A negative weight breaks Dijkstra's argument, so the Bellman–Ford method is used instead: relax every edge, ∣V∣−1|V| - 1 times over. A shortest path, if one exists, has at most ∣V∣−1|V| - 1 edges, so after that many rounds every distance is right. If one more round still improves something, there is a cycle of negative total weight within reach, and going round it again and again makes the "distance" as small as you like. Then no shortest path exists, and instead of a number the answer is the cycle, found by walking back along the last improvements. In an undirected graph a single negative edge already is such a cycle (walk it back and forth), so it is reported at once.

All pairs

const ap = allPairsShortestPaths(d);
ap.distance("s", "t").toString();    // "0"
ap.path("s", "t");                   // ["s", "b", "a", "t"]
ap.matrix;                           // Rationals, null where there is no path

The Floyd–Warshall method allows the vertices as stopovers one at a time: after step kk, entry (i,j)(i, j) holds the shortest distance from ii to jj using only the first kk vertices in between, by

dk(i,j)=min⁡(dk−1(i,j),  dk−1(i,k)+dk−1(k,j)). d_k(i, j) = \min\bigl(d_{k-1}(i, j),\; d_{k-1}(i, k) + d_{k-1}(k, j)\bigr).

That is ∣V∣3|V|^3 steps, simple and exact; a negative number on the diagonal at the end reveals a negative cycle, which is then found and returned as above.

The tests of this library compare all three methods with the minimum over every simple path, on several hundred random weighted graphs.

Try itEdit the code and run it with @ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs