How to detect if a directed graph is cyclic?

后端 未结 6 1785
鱼传尺愫
鱼传尺愫 2020-12-05 07:32

How can we detect if a directed graph is cyclic? I thought using breadth first search, but I\'m not sure. Any ideas?

6条回答
  •  渐次进展
    2020-12-05 07:46

    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;
      }
    

提交回复
热议问题