``` 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 ``` ```package algs44; import stdlib.*; import algs13.Stack; import algs42.Topological; /* *********************************************************************** * Compilation: javac AcyclicSP.java * Execution: java AcyclicSP V E * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java * Data files: http://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt * * Computes shortest paths in an edge-weighted acyclic digraph. * * Remark: should probably check that graph is a DAG before running * * % java AcyclicSP tinyEWDAG.txt 5 * 5 to 0 (0.73) 5->4 0.35 4->0 0.38 * 5 to 1 (0.32) 5->1 0.32 * 5 to 2 (0.62) 5->7 0.28 7->2 0.34 * 5 to 3 (0.61) 5->1 0.32 1->3 0.29 * 5 to 4 (0.35) 5->4 0.35 * 5 to 5 (0.00) * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52 * 5 to 7 (0.28) 5->7 0.28 * *************************************************************************/ public class AcyclicSP { private final double[] distTo; // distTo[v] = distance of shortest s->v path private final DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path public AcyclicSP(EdgeWeightedDigraph G, int s) { distTo = new double[G.V()]; edgeTo = new DirectedEdge[G.V()]; for (int v = 0; v < G.V(); v++) distTo[v] = Double.POSITIVE_INFINITY; distTo[s] = 0.0; // visit vertices in toplogical order Topological topological = new Topological(G); for (int v : topological.order()) { for (DirectedEdge e : G.adj(v)) relax(e); } } // relax edge e private void relax(DirectedEdge e) { int v = e.from(), w = e.to(); if (distTo[w] > distTo[v] + e.weight()) { distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; } } // return length of the shortest path from s to v, infinity if no such path public double distTo(int v) { return distTo[v]; } // is there a path from s to v? public boolean hasPathTo(int v) { return distTo[v] < Double.POSITIVE_INFINITY; } // return view of the shortest path from s to v, null if no such path public Iterable pathTo(int v) { if (!hasPathTo(v)) return null; Stack path = new Stack<>(); for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { path.push(e); } return path; } public static void main(String[] args) { In in = new In(args[0]); int s = Integer.parseInt(args[1]); EdgeWeightedDigraph G = new EdgeWeightedDigraph(in); // find shortest path from s to each other vertex in DAG AcyclicSP sp = new AcyclicSP(G, s); for (int v = 0; v < G.V(); v++) { if (sp.hasPathTo(v)) { StdOut.format("%d to %d (%.2f) ", s, v, sp.distTo(v)); for (DirectedEdge e : sp.pathTo(v)) { StdOut.print(e + " "); } StdOut.println(); } else { StdOut.format("%d to %d no path\n", s, v); } } } } ```