How to detect if a directed graph is cyclic?

后端 未结 6 1803
鱼传尺愫
鱼传尺愫 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:52

    Another simple solution would be a mark-and-sweep approach. Basically, for each node in tree you flag it as "visited" and then move on to it's children. If you ever see a node with the "visted" flag set, you know there's a cycle.

    If modifying the graph to include a "visited" bit isn't possible, a set of node pointers can be used instead. To flag a node as visited, you place a pointer to it in the set. If the pointer is already in the set, there's a cycle.

提交回复
热议问题