// Textbook fragment 13.09 /** This class specializes DFS to find a cycle. */ public class FindCycleDFS extends DFS> { protected PositionList cycle; // sequence of edges of the cycle protected boolean done; protected Vertex cycleStart; public void setup() { cycle = new NodePositionList(); done = false; } protected void startVisit(Vertex v) { cycle.addLast(v); } protected void finishVisit(Vertex v) { cycle.remove(cycle.last()); // remove v from cycle if (!cycle.isEmpty()) cycle.remove(cycle.last()); // remove edge into v from cycle } protected void traverseDiscovery(Edge e, Vertex from) { cycle.addLast(e); } protected void traverseBack(Edge e, Vertex from) { cycle.addLast(e); // back edge e creates a cycle cycleStart = graph.opposite(from, e); cycle.addLast(cycleStart); // first vertex completes the cycle done = true; } protected boolean isDone() { return done; } public Iterable finalResult(Iterable r) { // remove the vertices and edges from start to cycleStart if (!cycle.isEmpty()) { for (Position p: cycle.positions()) { if (p.element() == cycleStart) break; cycle.remove(p); // remove vertex from cycle } } return cycle; // list of the vertices and edges of the cycle } }