Here's my attempt. I iterate through each vertex in the graph and do a DFS to see if I reach back on a vertex I already visited in this vertex's iteration. It seems to work but I am not satisfied with how I short-circuit my code when it found a cycle using if clauses, could not think of a better way to do that.
public boolean isCyclic(Map<T, List<T>> adjacencyList) {
for (T node: adjacencyList.keySet()) {
Set<T> visited = new HashSet<>();
visited.add(node);
if (isCyclic(visited, node) == true)
return true;
}
return false;
}
private boolean isCyclic(Set<T> visited, T node) {
boolean retval;
for (T connectedNode: map.get(node)) {
if (visited.contains(connectedNode)) {
// We've reached back to a vertex, i.e. a back-edge
return true;
} else {
visited.add(connectedNode);
if (isCyclic(visited, connectedNode) == true)
return true;
}
}
return false;
}