

Detecting Cycles in a Directed Graph  - bdr
http://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html

======
SapphireSun
Another way to do it is to DFS or BFS a graph while marking nodes "visited" or
not. If you encounter a node in your search path that was marked, there's a
cycle. I think you did something extremely similar, but I'm not sure you
marked them or not. There might be a simpler way to do it wihtout so many
loops:

    
    
      # Initial condition is for all nodes: node.visited = False
    
      def detect_cycle( start ):
    
         if start.visited == True:
             return True
    
         start.visit = True
         cycle = False
         for child in start.children:
               cycle = cycle or detect_cycle( child )
         return cycle
    

Of course you might need some other stuff to be returned, in which case this
would be wholly inadequate ;-)

~~~
hc
this code does not work. it tests if the graph is a tree, not a directed
acyclic graph.

~~~
SapphireSun
You're right. Now that I think about it. Someone else mentioned that it
doesn't test for unconnected nodes, or nodes connected only via back links.

However, figuring out how to find them will depend heavily on your
implementation. Most likely you store all of them in an array and perform the
search on each of them. I wish I could find my data structures and algorithms
textbook. I lent it out and I really wish I still had it...

------
bdr
Posted for the Python and the discussion.

