new ArrayDeque<>(); for (int i=0; i<size(); i++) notVisited.add(i); while (!notVisited.isEmpty()) { if (containsCycleAux(notVisited.poll(), notVisited, new HashSet<>())) return true; } return false; } boolean containsCycleAux(int target, Deque<Integer> notVisited, Set<Integer> visited)