The following code works fine except for when it runs through an acyclic graph. It marks the acyclic graph as cyclic and I can't understand why.
@Override
public boolean isCyclic(DirectedGraph<T> graph) {
List<Node<T>> visitedNodes = new ArrayList<>();
int cycles = 0;
for (Node<T> node : graph) {
if (recNodeCycleCheck(node, visitedNodes)) {
cycles++;
}
visitedNodes = new ArrayList<>();
}
return cycles > 0;
}
private boolean recNodeCycleCheck(Node<T> node, List<Node<T>> visitedNodes) {
if (visitedNodes.contains(node)) {
return true;
}
visitedNodes.add(node);
for (Iterator<Node<T>> it = node.succsOf(); it.hasNext();) {
Node<T> currentNode = it.next();
if (visitedNodes.contains(currentNode)) {
return true;
}
if (recNodeCycleCheck(currentNode, visitedNodes)) {
return true;
}
}
return false;
}
I've tried to name the code as clear as possible so it should be easy to read. The first method isCyclic() receives a graph, and for each node in the graph it checks it's adjacent list and the successors of nodes within that list. If at any point they point back to an already visited node, the graph is cyclic.
This seems to work fine for all graphs except for the acyclic ones.
Any ideas what's going on?