# Graph – Find Cycle in Undirected Graph using Disjoint Set (Union-Find)

Objective: Given a graph, check if the graph contains a cycle using disjoint set.

Note: Disjoint-set data structure, also called a union–find data structure or merge–find set.

Example: Earlier in Detect Cycle in Undirected Graph using DFS we discussed about how to find cycle in graph using DFS. In this article we will discuss how to find cycle using disjoint-set.

How to find cycle:

• The makeset operation makes a new set by creating a new element with a parent pointer to itself.
• Then process each edge of the graph and perform find and Union operations to make subsets using both vertices of the edge.
• If find operation on both the vertices returns the same parent (means both vertices belongs to the same subset) then cycle is detected.

Lets walk through one example for more understanding, see the animation below:      find-union-1
find-union-2
find-union-3
find-union-4
find-union-5
find-union-6    Java Code:

 import java.util.ArrayList; import java.util.LinkedList; public class DisjointSet { static class Edge{ int source; int destination; public Edge(int source, int destination) { this.source = source; this.destination = destination; } } static class Graph{ int vertices; LinkedList[] adjList; ArrayList allEdges = new ArrayList<>(); Graph(int vertices){ this.vertices = vertices; adjList = new LinkedList[vertices]; for (int i = 0; i (); } } public void addEgde(int source, int destination){ Edge edge = new Edge(source, destination); adjList[source].addFirst(edge); allEdges.add(edge); //add to total edges } public void makeSet(int [] parent){ //Make set- creating a new element with a parent pointer to itself. for (int i = 0; i

Output:

```Graph contains cycle: true
```

Ref: wiki