Reputation: 8991
I have a hw problem that asks for an algorithm that detects if there is any cycle in any undirected graph that contains any given edge 'E'. The algorithm should run in O(N) linear time.
The problem I have is that I don't know where to start. I have some simple sample graphs but I dont know where to go from there.
Any hints?
Upvotes: 16
Views: 24247
Reputation: 11
Run DFS on G and do the following. Consider the first time the edge e is traversed.
There are two cases:
Upvotes: 0
Reputation: 181
Take out that edge (u,v) from G. 1. Run BFS to see if v is still reachable from u. 2. if yes, then the original graph has a cycle containing e. otherwise there is not.
Upvotes: 18
Reputation: 1
For the edge (u,v):
1- perform a depth first search starting from u, determine if v is found and a back edge exist along the path to v.
2- perform a depth first search from v, if u is found and back edge exist to u, then there's a cycle that includes both u and v.
In other words,
1- perform a DFS starting from u, check if back edge exist and v is not finished yet.
2- perform a DFS starting from v, check if back edge exist and u is not finished yet if both conditions are true, then edge(u,v) belong to a cycle.
Upvotes: 0
Reputation: 1355
Do a depth first search adding nodes to a list as you go, and removing them from the list as you return.
The list represents your current path of traversal.
If you come across a node that is already in your list, then there is a loop/cycle.
Upvotes: 3
Reputation: 9278
You start with the edge 'e'. From it you should get the two vertices it connects. From them you get other edges and other vertices, and other edges and other vertices, and... You'll need a way to figure out if a vertex has already been 'visited' by your algorithm. If it has then there's a cycle that 'e' is part of.
Upvotes: 1