Given an undirected graph, how to check if there is a cycle in the graph?
Java Algorithm – Detect cycle in an undirected graph
For example, the following graph has a cycle 1-0-2-1.
The time complexity of the union-find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect cycle in an undirected graph in O(V+E) time. We do a DFS traversal of the given graph. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle. The assumption of this approach is that there are no parallel edges between any two vertices.

The program is given in Java program, as follows
Java Programming:
import java.io.*;
import java.util.*;
class Graph
{
private int V;
private LinkedList<Integer> adj[];
Graph(int v) {
V = v;
adj = new LinkedList[v];
for(int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v,int w) {
adj[v].add(w);
adj[w].add(v);
}
Boolean isCyclicUtil(int v, Boolean visited[], int parent)
{
visited[v] = true;
Integer i;
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();
if (!visited[i])
{
if (isCyclicUtil(i, visited, v))
return true;
}
else if (i != parent)
return true;
}
return false;
}
Boolean isCyclic()
{
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int u = 0; u < V; u++)
if (!visited[u])
if (isCyclicUtil(u, visited, -1))
return true;
return false;
}
public static void main(String args[])
{
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 0);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (g1.isCyclic())
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
Graph g2 = new Graph(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
if (g2.isCyclic())
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't contains cycle");
}
}
Output:
Graph contains cycle
Graph doesn't contain cycle
Time Complexity: The program does a simple DFS Traversal of graph and graph is represented using adjacency list. So the time complexity is O(V+E)
[ad type=”banner”]