codezoned / ScriptsDump

The biggest dump of scripts ever!
http://www.codezoned.com/
143 stars 173 forks source link

cycle in an undirected graph #278

Closed prasantraj0808 closed 2 years ago

prasantraj0808 commented 2 years ago

Use DFS from every unvisited node. Depth First Traversal can be used to detect a cycle in a Graph. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is indirectly joining a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. To find the back edge to any of its ancestors keep a visited array and if there is a back edge to any visited node then there is a loop and return true.