Detecting cycles in undirected graph
I want to detect cycles in an undirected graph such that I get a list of all edges/vertices which form each cycle. For a graph G({a,b,c,d}, {a-b, b-c, c-d, d-a, b-d}) this would be {a, b, c, d}, {a, b, d}, {b, c, d}.
I have read this and I think that when the iterative pseudocode from Wikipedia finds a back-edge then I can say the graph has a cycle. But I don't know how to find out which vertices/edges the cycle consists of.
Can you please help with an algorithm which would take a graph as input (or the information from DFS) and output list of lists describing the cycles?
Asked By : A123321
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/13693
Answered By : AndrewK
You're almost there, but when you find a back edge you already have all the information you need to describe the cycle it forms. Also, there's a bit of a complication where you might find duplicate cycles. Or you might not. Do you consider {A, B, C} to be the same cycle as {C, B, A}? What about {B, C, A}? Depends on what you're doing, but let's assume they're equivalent.
So you've got a graph you're DFSing. .
And you go down one branch and detect a few cycles. Cool.
But you haven't explored all possibilities, so you unwind the stack and take the next branch. You find some more cycles. Groovy.
The adventure continues. You go down another path and find another cycle. Good.
No, wait. BAD. You've got two equivalent cycles. And when you unwind to having only explored A-B, and take A-B-E this time, that's going to reveal more duplicates. You'd need a way to get rid of those, if they are a problem in your application.
Post a Comment