How can we detect if a directed graph is cyclic? I thought using breadth first search, but I\'m not sure. Any ideas?
Use DFS to search if any path is cyclic
class Node { T value; List> adjacent; }
class Graph{
List> nodes;
public boolean isCyclicRec()
{
for (Node node : nodes)
{
Set> initPath = new HashSet<>();
if (isCyclicRec(node, initPath))
{
return true;
}
}
return false;
}
private boolean isCyclicRec(Node currNode, Set> path)
{
if (path.contains(currNode))
{
return true;
}
else
{
path.add(currNode);
for (Node node : currNode.adjacent)
{
if (isCyclicRec(node, path))
{
return true;
}
else
{
path.remove(node);
}
}
}
return false;
}