// by finding a cycle in predecessor graph private void findNegativeCycle() { int V = edgeTo.length; EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V); for (int v = 0; v < V; v++) if (edgeTo[v] != null) spt.addEdge(edgeTo[v]); EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(spt); cycle = finder.cycle(); }
/** * Returns a negative cycle, or {@code null} if there is no such cycle. * @return a negative cycle as an iterable of edges, * or {@code null} if there is no such cycle */ public Iterable<DirectedEdge> negativeCycle() { for (int v = 0; v < distTo.length; v++) { // negative cycle in v's predecessor graph if (distTo[v][v] < 0.0) { int V = edgeTo.length; EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V); for (int w = 0; w < V; w++) if (edgeTo[v][w] != null) spt.addEdge(edgeTo[v][w]); EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(spt); assert finder.hasCycle(); return finder.cycle(); } } return null; }
/** * 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"); } }