patternMinor
single algorithm to work on both directed and undirected graph to detect cycles?
Viewed 0 times
graphdirectedbothalgorithmsingleundirectedworkandcyclesdetect
Problem
I have been trying to implement an algorithm to detect cycles (probably how many of them) in a
Using
This link describes one approach for cycle detection. To my understanding this works for directed graphs.
This link has the code for cycle detection in undirected graphs. but I fail to understand how it ignores the back edge. That is it must ignore any cycles with two nodes, say D to C and C to D.
which means it must remember it parent as the DFS recurses. But the code does not seem take care of that.
Any suggestions welcome..
directed and undirected graph. That is the code should apply for both directed and undirected graphs.Using
DFS or topological sort is mostly recommended in various posts. But largely, everything is addressed for undirected graph. This link describes one approach for cycle detection. To my understanding this works for directed graphs.
This link has the code for cycle detection in undirected graphs. but I fail to understand how it ignores the back edge. That is it must ignore any cycles with two nodes, say D to C and C to D.
which means it must remember it parent as the DFS recurses. But the code does not seem take care of that.
Any suggestions welcome..
Solution
For a Directed Graph - we keep track of the recursion stack. For an edge (u,v), if we currently are processing u, and we see that v is in the recursion stack, then we have a Cycle.
For Undirected Graph - we look construct a parent array while we are traversing with DFS. Similar situation, for an edge (u,v) while processing u, if we see that v is Visited && not the parent of u, then we have a cycle.
I hope this helps!
For Undirected Graph - we look construct a parent array while we are traversing with DFS. Similar situation, for an edge (u,v) while processing u, if we see that v is Visited && not the parent of u, then we have a cycle.
I hope this helps!
Context
StackExchange Computer Science Q#18342, answer score: 2
Revisions (0)
No revisions yet.