How do I check if a directed graph is acyclic?

后端 未结 11 1745
野的像风
野的像风 2020-11-30 19:16

How do I check if a directed graph is acyclic? And how is the algorithm called? I would appreciate a reference.

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 19:22

    I know this is an old topic but for future searchers here is a C# implementation I created (no claim that it's most efficient!). This is designed to use a simple integer to identify each node. You can decorate that however you like provided your node object hashes and equals properly.

    For Very deep graphs this may have high overhead, as it creates a hashset at each node in depth (they are destroyed over breadth).

    You input the node from which you want to search and the path take to that node.

    • For a graph with a single root node you send that node and an empty hashset
    • For a graph having multiple root nodes you wrap this in a foreach over those nodes and pass a new empty hashset for each iteration
    • When checking for cycles below any given node, just pass that node along with an empty hashset

      private bool FindCycle(int node, HashSet path)
      {
      
          if (path.Contains(node))
              return true;
      
          var extendedPath = new HashSet(path) {node};
      
          foreach (var child in GetChildren(node))
          {
              if (FindCycle(child, extendedPath))
                  return true;
          }
      
          return false;
      }
      

提交回复
热议问题