001package algs44; 002import stdlib.*; 003import algs13.Stack; 004import algs42.Topological; 005/* *********************************************************************** 006 * Compilation: javac AcyclicSP.java 007 * Execution: java AcyclicSP V E 008 * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Topological.java 009 * Data files: http://algs4.cs.princeton.edu/44sp/tinyEWDAG.txt 010 * 011 * Computes shortest paths in an edge-weighted acyclic digraph. 012 * 013 * Remark: should probably check that graph is a DAG before running 014 * 015 * % java AcyclicSP tinyEWDAG.txt 5 016 * 5 to 0 (0.73) 5->4 0.35 4->0 0.38 017 * 5 to 1 (0.32) 5->1 0.32 018 * 5 to 2 (0.62) 5->7 0.28 7->2 0.34 019 * 5 to 3 (0.61) 5->1 0.32 1->3 0.29 020 * 5 to 4 (0.35) 5->4 0.35 021 * 5 to 5 (0.00) 022 * 5 to 6 (1.13) 5->1 0.32 1->3 0.29 3->6 0.52 023 * 5 to 7 (0.28) 5->7 0.28 024 * 025 *************************************************************************/ 026 027public class AcyclicSP { 028 private final double[] distTo; // distTo[v] = distance of shortest s->v path 029 private final DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path 030 031 public AcyclicSP(EdgeWeightedDigraph G, int s) { 032 distTo = new double[G.V()]; 033 edgeTo = new DirectedEdge[G.V()]; 034 for (int v = 0; v < G.V(); v++) 035 distTo[v] = Double.POSITIVE_INFINITY; 036 distTo[s] = 0.0; 037 038 // visit vertices in toplogical order 039 Topological topological = new Topological(G); 040 for (int v : topological.order()) { 041 for (DirectedEdge e : G.adj(v)) 042 relax(e); 043 } 044 } 045 046 // relax edge e 047 private void relax(DirectedEdge e) { 048 int v = e.from(), w = e.to(); 049 if (distTo[w] > distTo[v] + e.weight()) { 050 distTo[w] = distTo[v] + e.weight(); 051 edgeTo[w] = e; 052 } 053 } 054 055 // return length of the shortest path from s to v, infinity if no such path 056 public double distTo(int v) { 057 return distTo[v]; 058 } 059 060 // is there a path from s to v? 061 public boolean hasPathTo(int v) { 062 return distTo[v] < Double.POSITIVE_INFINITY; 063 } 064 065 // return view of the shortest path from s to v, null if no such path 066 public Iterable<DirectedEdge> pathTo(int v) { 067 if (!hasPathTo(v)) return null; 068 Stack<DirectedEdge> path = new Stack<>(); 069 for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { 070 path.push(e); 071 } 072 return path; 073 } 074 075 076 077 public static void main(String[] args) { 078 In in = new In(args[0]); 079 int s = Integer.parseInt(args[1]); 080 EdgeWeightedDigraph G = new EdgeWeightedDigraph(in); 081 082 // find shortest path from s to each other vertex in DAG 083 AcyclicSP sp = new AcyclicSP(G, s); 084 for (int v = 0; v < G.V(); v++) { 085 if (sp.hasPathTo(v)) { 086 StdOut.format("%d to %d (%.2f) ", s, v, sp.distTo(v)); 087 for (DirectedEdge e : sp.pathTo(v)) { 088 StdOut.print(e + " "); 089 } 090 StdOut.println(); 091 } 092 else { 093 StdOut.format("%d to %d no path\n", s, v); 094 } 095 } 096 } 097}