Union | Python3 program to implement Union - Find with union by rank and path compression . ; Arr to represent parent of index i ; Size to represent the number of nodes in subgxrph rooted at index i ; set parent of every node to itself and size of node to one ; Each time we follow a path , find function compresses it further until the path length is greater than or equal to 1. ; while we reach a node whose parent is equal to itself ; Skip one level ; Move to the new level ; A function that does union of two nodes x and y where xr is root node of x and yr is root node of y ; Make yr parent of xr ; Make xr parent of yr ; The main function to check whether a given graph contains cycle or not ; Itexrte through all edges of gxrph , find nodes connecting them . If root nodes of both are same , then there is cycle in gxrph . ; find root of i ; find root of adj [ i ] [ j ] ; If same parent ; Make them connect ; Driver Code ; Initialize the values for arxry Arr and Size ; Adjacency list for graph ; call is_cycle to check if it contains cycle
MAX_VERTEX = 101 NEW_LINE Arr = [ None ] * MAX_VERTEX NEW_LINE size = [ None ] * MAX_VERTEX NEW_LINE def initialize ( n ) : NEW_LINE INDENT global Arr , size NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT Arr [ i ] = i NEW_LINE size [ i ] = 1 NEW_LINE DEDENT DEDENT def find ( i ) : NEW_LINE INDENT global Arr , size NEW_LINE while ( Arr [ i ] != i ) : NEW_LINE INDENT Arr [ i ] = Arr [ Arr [ i ] ] NEW_LINE i = Arr [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def _union ( xr , yr ) : NEW_LINE INDENT global Arr , size NEW_LINE DEDENT if ( size [ xr ] < size [ yr ] ) : NEW_LINE INDENT Arr [ xr ] = Arr [ yr ] NEW_LINE size [ yr ] += size [ xr ] NEW_LINE DEDENT else : NEW_LINE INDENT Arr [ yr ] = Arr [ xr ] NEW_LINE size [ xr ] += size [ yr ] NEW_LINE DEDENT def isCycle ( adj , V ) : NEW_LINE INDENT global Arr , size NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( len ( adj [ i ] ) ) : NEW_LINE DEDENT DEDENT x = find ( i ) NEW_LINE y = find ( adj [ i ] [ j ] ) NEW_LINE INDENT if ( x == y ) : NEW_LINE DEDENT return 1 NEW_LINE _union ( x , y ) NEW_LINE INDENT return 0 NEW_LINE DEDENT V = 3 NEW_LINE initialize ( V ) NEW_LINE adj = [ [ ] for i in range ( V ) ] NEW_LINE adj [ 0 ] . append ( 1 ) NEW_LINE adj [ 0 ] . append ( 2 ) NEW_LINE adj [ 1 ] . append ( 2 ) NEW_LINE if ( isCycle ( adj , V ) ) : NEW_LINE INDENT print ( " Graph ▁ contains ▁ Cycle . " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Graph ▁ does ▁ not ▁ contain ▁ Cycle . " ) NEW_LINE DEDENT