GraphUtil { public static <V, E> boolean isSimpleCycle(UndirectedGraph<V, E> graph) { if (graph.getVertexCount() < 3 || graph.getEdgeCount() < graph.getVertexCount()) { return false; } V v = graph.getVertices().iterator().next(); Set<V> visited = new HashSet<V>(); visited.add(v); while (graph.getNeighborCount(v) == 2 && !visited.containsAll(graph.getNeighbors(v))) { Iterator<V> iterator = graph.getNeighbors(v).iterator(); V v1 = iterator.next(); V v2 = iterator.next(); if (!visited.contains(v1)) { v = v1; visited.add(v1); } else { v = v2; visited.add(v2); } } return visited.containsAll(graph.getVertices()); }  static void addVertices(Graph<V, E> graph, Collection<V> vertices); static void copyGraph(Graph<V, E> source, Graph<V, E> target); static void copyTree(Tree<V, E> source, Tree<V, E> target); static boolean isDescendant(Tree<V, E> t, V v, V w); static boolean isWeaklyConnected(Hypergraph<V, E> graph); static boolean areVerticesWeaklyConnected(Hypergraph<V, E> studyGraph, V first, V second); static boolean isSimpleCycle(UndirectedGraph<V, E> graph); static V findCommonAncestor(Tree<V, E> tree, V u, V v); static List<V> findPath(Tree<V, E> tree, V u, V v);  }
@Test public void testIsSimpleCycle() { UndirectedGraph<String, Integer> graph = new UndirectedSparseGraph<String, Integer>(); graph.addVertex("C"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.removeVertex("C"); graph.addEdge(1, "A", "B"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.addEdge(2, "A", "C"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.addEdge(3, "C", "B"); assertTrue(GraphUtil.isSimpleCycle(graph)); graph.addVertex("D"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.addEdge(4, "B", "D"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.addEdge(5, "D", "C"); assertFalse(GraphUtil.isSimpleCycle(graph)); graph.removeEdge(3); assertTrue(GraphUtil.isSimpleCycle(graph)); }