001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package algs41;
import stdlib.*;
import algs13.Stack;
/* ***********************************************************************
 *  Compilation:  javac Cycle.java
 *  Dependencies: Graph.java Stack.java
 *
 *  Identifies a cycle.
 *  Runs in O(E + V) time.
 *
 *************************************************************************/

public class Cycle {
  private boolean[] marked;
  private int[] edgeTo;
  private Stack<Integer> cycle;

  public Cycle(Graph G) {
    if (hasSelfLoop(G)) return;
    if (hasParallelEdges(G)) return;
    marked = new boolean[G.V()];
    edgeTo = new int[G.V()];
    for (int v = 0; v < G.V(); v++)
      if (!marked[v] && hasCycleFrom(G, -1, v))
        return;
  }

  // Assuming there is no self loop or parallel edges, does this graph have a cycle?
  private boolean hasCycleFromSimple(Graph G, int u, int v) {
    marked[v] = true; 
    for (int w : G.adj(v)) {
      if (w == u) continue; // skip the back edge: edgeTo[v] = u
      if (marked[w]) return true; // been here before
      if (hasCycleFromSimple (G, v, w)) return true; // search recursively
    }
    return false;
  }

  // Assuming there is no self loop or parallel edges, does this graph have a cycle?
  // side effect: initialize cycle field
  private boolean hasCycleFrom(Graph G, int u, int v) {
    //StdOut.format ("dfs(%d, %d)\n", u, v);
    marked[v] = true;
    edgeTo[v] = u;
    for (int w : G.adj(v)) {
      if (w == u) continue; // skip the back edge
      if (marked[w]) {        
        cycle = new Stack<>();
        cycle.push(w);
        for (int   x = v; x != w; x = edgeTo[x])
          cycle.push(x);
        cycle.push(w);
        return true;
      }
      if (hasCycleFrom (G, v, w)) return true;
    }
    return false;
  }
  private boolean TEXTBOOKhasCycleFrom(Graph G, int u, int v) {
    marked[v] = true;
    edgeTo[v] = u;
    for (int w : G.adj(v)) {
      if ((marked[w] && w != u) || (!marked[w] && hasCycleFrom (G, v, w))) {
        if (cycle == null) {
          cycle = new Stack<>();
          cycle.push(w);
          for (int x = v; x != w; x = edgeTo[x])
            cycle.push(x);
          cycle.push(w);
        }
        return true;
      }
    }
    return false;
  }
  // does this graph have a self loop?
  // side effect: initialize cycle field
  private boolean hasSelfLoop(Graph G) {
    for (int v = 0; v < G.V(); v++) {
      for (int w : G.adj(v)) {
        if (v == w) {
          cycle = new Stack<>();
          cycle.push(v);
          cycle.push(v);
          return true;
        }
      }
    }
    return false;
  }

  // does this graph have two parallel edges?
  // side effect: initialize cycle field
  private boolean hasParallelEdges(Graph G) {
    for (int v = 0; v < G.V(); v++) {
      boolean[] marked = new boolean[G.V()];
      for (int w : G.adj(v)) {
        if (!marked[w]) {
          marked[w] = true;
        } else {
          // edge occurs twice
          cycle = new Stack<>();
          cycle.push(v);
          cycle.push(w);
          cycle.push(v);
          return true;
        }
      }
    }
    return false;
  }

  public boolean hasCycle()        { return cycle != null; }
  public Iterable<Integer> cycle() { return cycle;         }

  // test client
  public static void main(String[] args) {
    //    args = new String [] { "10", "5" };
    //    final int V = Integer.parseInt(args[0]);
    //    final int E = Integer.parseInt(args[1]);
    //    final Graph G = GraphGenerator.simple(V, E);
    //    StdOut.println(G);

    //args = new String [] { "data/tinyAG.txt" };
    args = new String [] { "data/tinyG.txt" };
    In in = new In(args[0]);
    Graph G = GraphGenerator.fromIn (in);
    StdOut.println(G);
    G.toGraphviz ("g.png");

    Cycle finder = new Cycle(G);
    if (finder.hasCycle()) {
      for (int v : finder.cycle()) {
        StdOut.print(v + " ");
      }
      StdOut.println();
    }
    else {
      StdOut.println("Graph is acyclic");
    }
  }


}