Generate an array from given pairs of adjacent elements | Java program of the above approach ; Utility function to find original array ; Map to store all neighbors for each element ; Vector to store original elements ; Stotrs which array elements are visited ; Adjacency list to store neighbors of each array element ; Find the first corner element ; Stores first element of the original array ; Push it into the original array ; Mark as visited ; Traversing the neighbors and check if the elements are visited or not ; Traverse adjacent elements ; If element is not visited ; Push it into res ; Mark as visited ; Update the next adjacent ; Print original array ; Driver Code ; Given pairs of adjacent elements
import java . io . * ; import java . util . * ; class Pair { int first , second ; Pair ( int first , int second ) { this . first = first ; this . second = second ; } } class GFG { static void find_original_array ( List < Pair > A ) { @ SuppressWarnings ( " unchecked " ) Map < Integer , List < Integer > > mp = new HashMap ( ) ; List < Integer > res = new ArrayList < Integer > ( ) ; @ SuppressWarnings ( " unchecked " ) Map < Integer , Boolean > visited = new HashMap ( ) ; for ( Pair it : A ) { List < Integer > temp ; temp = ( mp . containsKey ( it . first ) ) ? mp . get ( it . first ) : new ArrayList < Integer > ( ) ; temp . add ( it . second ) ; mp . put ( it . first , temp ) ; temp = ( mp . containsKey ( it . second ) ) ? mp . get ( it . second ) : new ArrayList < Integer > ( ) ; temp . add ( it . first ) ; mp . put ( it . second , temp ) ; } int it = 0 ; for ( Map . Entry < Integer , List < Integer > > entry : mp . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) == 1 ) { it = entry . getKey ( ) ; } } int adjacent = it ; res . add ( it ) ; visited . put ( it , true ) ; while ( res . size ( ) != A . size ( ) + 1 ) { for ( int elements : mp . get ( adjacent ) ) { if ( ! visited . containsKey ( elements ) ) { res . add ( elements ) ; visited . put ( elements , true ) ; adjacent = elements ; } } } for ( int val : res ) { System . out . print ( val + " ▁ " ) ; } } public static void main ( String [ ] args ) { @ SuppressWarnings ( " unchecked " ) List < Pair > A = new ArrayList ( ) ; A . add ( new Pair ( 5 , 1 ) ) ; A . add ( new Pair ( 3 , 4 ) ) ; A . add ( new Pair ( 3 , 5 ) ) ; find_original_array ( A ) ; } }