Replace each vertex with it 's  corresponding parent except  the root vertex
if ( parent [ Vertices [ k ] ] != 0 ) { Vertices [ k ] = parent [ Vertices [ k ] ] ; } } bool ans = true ; bool flag ; for ( int k = 0 ; k < V ; k ++ ) {