private boolean findCycleWithBfs(Vertex current, Vertex to, Set<Vertex> ignoreSet) { Set<Vertex> neighbours = data.get(current); for (Vertex neighbour : neighbours) { if (ignoreSet.contains(neighbour)) { continue; } if (neighbour.equals(to)) { return true; } Set<Vertex> newIgnoreSet = new HashSet<>(ignoreSet); newIgnoreSet.add(neighbour); boolean foundCycle = findCycleWithBfs(neighbour, to, newIgnoreSet); if (foundCycle) { return true; } } return false; }
/** * Essentially uses bfs to find if there exists a cycle between two vertices of the new edge. * * @param edge edge for which we are looking a cycle * @return true if there exists a cycle. false otherwise */ private boolean hasCycle(Edge edge) { // if any of two vertices of the edge is not already in the disjoint set then there can't be a // cycle either if (!data.containsKey(edge.getFrom()) || !data.containsKey(edge.getTo())) { return false; } Set<Vertex> fromNeighbours = data.get(edge.getFrom()); for (Vertex neighbour : fromNeighbours) { boolean foundCycle = false; if (!neighbour.equals(edge.getTo())) { Set<Vertex> set = new HashSet<>(); set.add(neighbour); foundCycle = findCycleWithBfs(neighbour, edge.getTo(), set); } if (foundCycle) { return true; } } return false; }