views:

846

answers:

3

Given an undirected graph what is the best algorithm to detect if it contains a cycle or not?

A breadth first or depth first search while keeping track of visited nodes is one method, but it's O(n^2). Is there anything faster?

+2  A: 

The BFS and DFS algorithm for given graph G(V,E) has time complexity of O(|V|+|E|). So as you can see it's linear dependency of input. You can perform some heuristics in case you have very specialized graph, but in general it's not so bad to use DFS for that. You can check for some information here. Anyway you have to traverse the whole graph.

Artem Barger
Thanks, I guess I ignored the fact that the set of all visited nodes is very much small at the beginning and grows only as the algorithm proceeds.
Frederick
A: 

Testing for the presence of a cycle in a graph G(V,E) using Depth First Search is O(|V|,|E|) if the graph is represented using an adjacency list.

It is necessary to traverse the entire graph to show there are no cycles. If you are simply interested in the presence/absence of a cycle, you can obviously finish at the point a cycle is discovered.

mealnor
+1  A: 

Here's your O(V) algorithm:

def hasCycles(G, V, E): 
    if E>=V:
        return True
    else:
        # here E<V
        # perform O(E+V) = O(V) algorithm 
        ...

The ... can be performed with DFS. If you have E<V and edges are stored in a meaningful way (as a list), you can probably do O(E)+logs which would make the whole algorithm O(min(E,V))+logs.

Hope you like this answer, though a bit late!

ilya n.
As you see, I heavily use the fact that an undirected graph without cycles is a subgraph of a tree and thus must have E<V
ilya n.