Construct a graph which does not contain any pair of adjacent nodes with same value | Java program for the above approach ; Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second unique element ; Function to construct the graph such that the every adjacent nodes have different value ; Stores pair of edges formed ; Stores first unique occurrence ; Check for the second unique occurrence ; Store indices of 2 nd unique occurrence ; To check if arr has only 1 unique element or not ; Store the connections of all unique elements with Node 1 ; If value at node ( i + 1 ) is same as value at Node 1 then store its indices ; If count is zero then it 's not  possible to construct the graph ; If more than 1 unique element is present ; Print the edges ; Driver Code ; Given array having node values ; Function Call
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printConnections ( Vector < pair > store , Vector < Integer > ind , int ind1 ) { for ( pair pr : store ) { System . out . print ( pr . first + " ▁ " + pr . second + "NEW_LINE"); } if ( ind . size ( ) != 0 ) { for ( int x : ind ) { System . out . print ( ind1 + " ▁ " + ( x + 1 ) + "NEW_LINE"); } } } static void constructGraph ( char arr [ ] , int N ) { Vector < Integer > ind = new Vector < > ( ) ; Vector < pair > store = new Vector < > ( ) ; char x = arr [ 0 ] ; int count = 0 ; int ind1 = - 1 ; for ( int i = 1 ; i <= N - 1 ; ++ i ) { if ( arr [ i ] != x ) { ind1 = i + 1 ; count ++ ; store . add ( new pair ( 1 , i + 1 ) ) ; } else { ind . add ( i ) ; } } if ( count == 0 ) { System . out . print ( " Not ▁ Possible " ) ; } else { System . out . print ( " Possible " + "NEW_LINE"); printConnections ( store , ind , ind1 ) ; } } public static void main ( String [ ] args ) { int N = 5 ; char arr [ ] = { ' a ' , ' b ' , ' a ' , ' b ' , ' c ' } ; constructGraph ( arr , N ) ; } }