Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)

17 Jun, 2022
A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. A union-find algorithm is an algorithm that performs two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.
Union: Join two subsets into a single subset. Here first we have to check if the two subsets belong to same set. If no, then we cannot perform union.
In this post, we will discuss the application of Disjoint Set Data Structure. The application is to check whether a given graph contains a cycle or not.
Union-Find Algorithm can be used to check whether an undirected graph contains cycle or not. Note that we have discussed an algorithm to detect cycle. This is another method based on Union-Find. This method assumes that the graph doesn’t contain any self-loops. 
We can keep track of the subsets in a 1D array, let’s call it parent[].Let us consider the following graph: 
For each edge, make subsets using both the vertices of the edge. If both the vertices are in the same subset, a cycle is found.
Initially, all slots of parent array are initialized to -1 (means there is only one item in every subset).
0   1   2
-1 -1  -1
Now process all edges one by one.Edge 0-1: Find the subsets in which vertices 0 and 1 are. Since they are in different subsets, we take the union of them. For taking the union, either make node 0 as parent of node 1 or vice-versa. 
0   1   2    <----- 1 is made parent of 0 (1 is now representative of subset {0, 1})
1  -1  -1
Edge 1-2: 1 is in subset 1 and 2 is in subset 2. So, take union.
0   1   2    <----- 2 is made parent of 1 (2 is now representative of subset {0, 1, 2})
1   2  -1
Edge 0-2: 0 is in subset 2 and 2 is also in subset 2. Hence, including this edge forms a cycle.How subset of 0 is same as 2? 0->1->2 // 1 is parent of 0 and 2 is parent of 1  
Based on the above explanation, below are implementations: 
C++
C
Java
Python3
C#
Javascript
// A union-find algorithm to detect cycle in a graph#include <bits/stdc++.h>using namespace std; // a structure to represent an edge in graphclass Edge{public:    int src, dest;}; // a structure to represent a graphclass Graph{public:    // V-> Number of vertices, E-> Number of edges    int V, E;     // graph is represented as an array of edges    Edge* edge;}; // Creates a graph with V vertices and E edgesGraph* createGraph(int V, int E){    Graph* graph = new Graph();    graph->V = V;    graph->E = E;     graph->edge = new Edge[graph->E * sizeof(Edge)];     return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){    if (parent[i] == -1)        return i;    return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){    parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle(Graph* graph){    // Allocate memory for creating V subsets    int* parent = new int[graph->V * sizeof(int)];     // Initialize all subsets as single element sets    memset(parent, -1, sizeof(int) * graph->V);     // Iterate through all edges of graph, find subset of    // both vertices of every edge, if both subsets are    // same, then there is cycle in graph.    for (int i = 0; i < graph->E; ++i) {        int x = find(parent, graph->edge[i].src);        int y = find(parent, graph->edge[i].dest);         if (x == y)            return 1;         Union(parent, x, y);    }    return 0;} // Driver codeint main(){    /* Let us create the following graph        0        | \        |  \        1---2 */    int V = 3, E = 3;    Graph* graph = createGraph(V, E);     // add edge 0-1    graph->edge[0].src = 0;    graph->edge[0].dest = 1;     // add edge 1-2    graph->edge[1].src = 1;    graph->edge[1].dest = 2;     // add edge 0-2    graph->edge[2].src = 0;    graph->edge[2].dest = 2;     if (isCycle(graph))        cout << "graph contains cycle";    else        cout << "graph doesn't contain cycle";     return 0;} // This code is contributed by rathbhupendra
// A union-find algorithm to detect cycle in a graph#include <stdio.h>#include <stdlib.h>#include <string.h> // a structure to represent an edge in graphstruct Edge{    int src, dest;}; // a structure to represent a graphstruct Graph{    // V-> Number of vertices, E-> Number of edges    int V, E;     // graph is represented as an array of edges    struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){    struct Graph* graph =           (struct Graph*) malloc( sizeof(struct Graph) );    graph->V = V;    graph->E = E;     graph->edge =        (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );     return graph;} // A utility function to find the subset of an element iint find(int parent[], int i){    if (parent[i] == -1)        return i;    return find(parent, parent[i]);} // A utility function to do union of two subsetsvoid Union(int parent[], int x, int y){    parent[x] = y;} // The main function to check whether a given graph contains// cycle or notint isCycle( struct Graph* graph ){    // Allocate memory for creating V subsets    int *parent = (int*) malloc( graph->V * sizeof(int) );     // Initialize all subsets as single element sets    memset(parent, -1, sizeof(int) * graph->V);     // Iterate through all edges of graph, find subset of both    // vertices of every edge, if both subsets are same, then    // there is cycle in graph.    for(int i = 0; i < graph->E; ++i)    {        int x = find(parent, graph->edge[i].src);        int y = find(parent, graph->edge[i].dest);         if (x == y)            return 1;         Union(parent, x, y);    }    return 0;} // Driver program to test above functionsint main(){    /* Let us create the following graph        0        | \        |  \        1---2 */     int V = 3, E = 3;    struct Graph* graph = createGraph(V, E);     // add edge 0-1    graph->edge[0].src = 0;    graph->edge[0].dest = 1;     // add edge 1-2    graph->edge[1].src = 1;    graph->edge[1].dest = 2;     // add edge 0-2    graph->edge[2].src = 0;    graph->edge[2].dest = 2;     if (isCycle(graph))        printf( "graph contains cycle" );    else        printf( "graph doesn't contain cycle" );     return 0;}
// Java Program for union-find algorithm to detect cycle in a graphimport java.util.*;import java.lang.*;import java.io.*; class Graph{    int V, E;    // V-> no. of vertices & E->no.of edges    Edge edge[]; // /collection of all edges     class Edge    {        int src, dest;    };     // Creates a graph with V vertices and E edges    Graph(int v,int e)    {        V = v;        E = e;        edge = new Edge[E];        for (int i=0; i<e; ++i)            edge[i] = new Edge();    }     // A utility function to find the subset of an element i    int find(int parent[], int i)    {        if (parent[i] == -1)            return i;        return find(parent, parent[i]);    }     // A utility function to do union of two subsets    void Union(int parent[], int x, int y)    {        parent[x] = y;    }      // The main function to check whether a given graph    // contains cycle or not    int isCycle( Graph graph)    {        // Allocate memory for creating V subsets        int parent[] = new int[graph.V];         // Initialize all subsets as single element sets        for (int i=0; i<graph.V; ++i)            parent[i]=-1;         // Iterate through all edges of graph, find subset of both        // vertices of every edge, if both subsets are same, then        // there is cycle in graph.        for (int i = 0; i < graph.E; ++i)        {            int x = graph.find(parent, graph.edge[i].src);            int y = graph.find(parent, graph.edge[i].dest);             if (x == y)                return 1;             graph.Union(parent, x, y);        }        return 0;    }     // Driver Method    public static void main (String[] args)    {        /* Let us create the following graph        0        | \        |  \        1---2 */        int V = 3, E = 3;        Graph graph = new Graph(V, E);         // add edge 0-1        graph.edge[0].src = 0;        graph.edge[0].dest = 1;         // add edge 1-2        graph.edge[1].src = 1;        graph.edge[1].dest = 2;         // add edge 0-2        graph.edge[2].src = 0;        graph.edge[2].dest = 2;         if (graph.isCycle(graph)==1)            System.out.println( "graph contains cycle" );        else            System.out.println( "graph doesn't contain cycle" );    }}
# Python Program for union-find algorithm to detect cycle in a undirected graph# we have one egde for any two vertex i.e 1-2 is either 1-2 or 2-1 but not both  from collections import defaultdict  #This class represents a undirected graph using adjacency list representationclass Graph:      def __init__(self,vertices):        self.V= vertices #No. of vertices        self.graph = defaultdict(list) # default dictionary to store graph       # function to add an edge to graph    def addEdge(self,u,v):        self.graph[u].append(v)      # A utility function to find the subset of an element i    def find_parent(self, parent,i):        if parent[i] == -1:            return i        if parent[i]!= -1:             return self.find_parent(parent,parent[i])     # A utility function to do union of two subsets    def union(self,parent,x,y):        parent[x] = y         # The main function to check whether a given graph    # contains cycle or not    def isCyclic(self):                 # Allocate memory for creating V subsets and        # Initialize all subsets as single element sets        parent = [-1]*(self.V)         # Iterate through all edges of graph, find subset of both        # vertices of every edge, if both subsets are same, then        # there is cycle in graph.        for i in self.graph:            for j in self.graph[i]:                x = self.find_parent(parent, i)                y = self.find_parent(parent, j)                if x == y:                    return True                self.union(parent,x,y)  # Create a graph given in the above diagramg = Graph(3)g.addEdge(0, 1)g.addEdge(1, 2)g.addEdge(2, 0) if g.isCyclic():    print ("Graph contains cycle")else :    print ("Graph does not contain cycle ")  #This code is contributed by Neelam Yadav
// C# Program for union-find// algorithm to detect cycle// in a graphusing System;class Graph{ // V-> no. of vertices &// E->no.of edges public int V, E;    // collection of all edgespublic Edge []edge; class Edge{  public int src, dest;}; // Creates a graph with V// vertices and E edgespublic  Graph(int v,int e){  V = v;  E = e;  edge = new Edge[E];     for (int i = 0; i < e; ++i)    edge[i] = new Edge();} // A utility function to find// the subset of an element iint find(int []parent, int i){  if (parent[i] == -1)    return i;  return find(parent,              parent[i]);} // A utility function to do// union of two subsetsvoid Union(int []parent,           int x, int y){  parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notint isCycle(Graph graph){  // Allocate memory for  // creating V subsets  int []parent =        new int[graph.V];   // Initialize all subsets as  // single element sets  for (int i = 0; i < graph.V; ++i)    parent[i] =- 1;   // Iterate through all edges of graph,  // find subset of both vertices of every  // edge, if both subsets are same, then  // there is cycle in graph.  for (int i = 0; i < graph.E; ++i)  {    int x = graph.find(parent,                       graph.edge[i].src);    int y = graph.find(parent,                       graph.edge[i].dest);     if (x == y)      return 1;     graph.Union(parent, x, y);  }  return 0;} // Driver codepublic static void Main(String[] args){  /* Let us create the following graph        0        | \        |  \        1---2 */  int V = 3, E = 3;  Graph graph = new Graph(V, E);   // add edge 0-1  graph.edge[0].src = 0;  graph.edge[0].dest = 1;   // add edge 1-2  graph.edge[1].src = 1;  graph.edge[1].dest = 2;   // add edge 0-2  graph.edge[2].src = 0;  graph.edge[2].dest = 2;   if (graph.isCycle(graph) == 1)    Console.WriteLine("graph contains cycle");  else    Console.WriteLine("graph doesn't contain cycle");}} // This code is contributed by Princi Singh
<script> // Javascript program for union-find// algorithm to detect cycle// in a graph // V-> no. of vertices &// E->no.of edges var V, E;    // Collection of all edgesvar edge; class Edge{    constructor()    {        this.src = 0;        this.dest = 0;    }}; // Creates a graph with V// vertices and E edgesfunction initialize(v,e){    V = v;    E = e;    edge = Array.from(Array(E), () => Array());} // A utility function to find// the subset of an element ifunction find(parent, i){    if (parent[i] == -1)        return i;             return find(parent,                parent[i]);} // A utility function to do// union of two subsetsfunction Union(parent, x, y){    parent[x] = y;} // The main function to check// whether a given graph// contains cycle or notfunction isCycle(){         // Allocate memory for    // creating V subsets    var parent = Array(V).fill(0);         // Initialize all subsets as    // single element sets    for(var i = 0; i < V; ++i)        parent[i] =- 1;         // Iterate through all edges of graph,    // find subset of both vertices of every    // edge, if both subsets are same, then    // there is cycle in graph.    for (var i = 0; i < E; ++i)    {        var x = find(parent,                     edge[i].src);        var y = find(parent,                     edge[i].dest);                 if (x == y)            return 1;                 Union(parent, x, y);    }    return 0;} // Driver code/* Let us create the following graph      0      | \      |  \      1---2 */var V = 3, E = 3;initialize(V, E); // Add edge 0-1edge[0].src = 0;edge[0].dest = 1; // Add edge 1-2edge[1].src = 1;edge[1].dest = 2; // Add edge 0-2edge[2].src = 0;edge[2].dest = 2; if (isCycle() == 1)    document.write("graph contains cycle");else    document.write("graph doesn't contain cycle");     // This code is contributed by rutvik_56 </script>
graph contains cycle
Note that the implementation of union() and find() is naive and takes O(n) time in the worst case. These methods can be improved to O(Logn) using Union by Rank or Height. We will soon be discussing Union by Rank in a separate post. 
Union-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersUnion-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mHz-mx-8lJ8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Articles : Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Disjoint Set Data Structures (Java Implementation) Greedy Algorithms | Set 2 (Kruskal’s Minimum Spanning Tree Algorithm) Job Sequencing Problem | Set 2 (Using Disjoint Set)
avinashr175
KhushalVyas
rathbhupendra
f2008700
princi singh
rahulsharma9
gsivaram1998
rutvik_56
vector01
amartyaghoshgfg
hardikkoriintern
graph-cycle
union-find
Graph
Graph
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Floyd Warshall Algorithm | DP-16
What is Data Structure: Types, Classifications and Applications