/** * Determines whether the edge-weighted digraph {@code G} has a topological * order and, if so, finds such an order. * @param G the edge-weighted digraph */ public Topological(EdgeWeightedDigraph G) { EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(G); order = dfs.reversePost(); } }
/** * Unit tests the {@code EdgeWeightedDirectedCycle} data type. * * @param args the command-line arguments */ public static void main(String[] args) { // create random DAG with V vertices and E edges; then add F random edges int V = Integer.parseInt(args[0]); int E = Integer.parseInt(args[1]); int F = Integer.parseInt(args[2]); EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); int[] vertices = new int[V]; for (int i = 0; i < V; i++) vertices[i] = i; StdRandom.shuffle(vertices); for (int i = 0; i < E; i++) { int v, w; do { v = StdRandom.uniform(V); w = StdRandom.uniform(V); } while (v >= w); double weight = StdRandom.uniform(); G.addEdge(new DirectedEdge(v, w, weight)); } // add F extra edges for (int i = 0; i < F; i++) { int v = StdRandom.uniform(V); int w = StdRandom.uniform(V); double weight = StdRandom.uniform(0.0, 1.0); G.addEdge(new DirectedEdge(v, w, weight)); } StdOut.println(G); // find a directed cycle EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); if (finder.hasCycle()) { StdOut.print("Cycle: "); for (DirectedEdge e : finder.cycle()) { StdOut.print(e + " "); } StdOut.println(); } // or give topologial sort else { StdOut.println("No directed cycle"); } }