Generate an array from given pairs of adjacent elements | C # 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
using System ; using System . Collections . Generic ; public class Pair { public int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } public class GFG { static void find_original_array ( List < Pair > A ) { Dictionary < int , List < int > > mp = new Dictionary < int , List < int > > ( ) ; List < int > res = new List < int > ( ) ; Dictionary < int , bool > visited = new Dictionary < int , bool > ( ) ; foreach ( Pair it in A ) { List < int > temp ; temp = ( mp . ContainsKey ( it . first ) ) ? mp [ it . first ] : new List < int > ( ) ; temp . Add ( it . second ) ; if ( ! mp . ContainsKey ( it . first ) ) mp . Add ( it . first , temp ) ; else mp [ it . first ] = temp ; temp = ( mp . ContainsKey ( it . second ) ) ? mp [ it . second ] : new List < int > ( ) ; temp . Add ( it . first ) ; if ( ! mp . ContainsKey ( it . second ) ) mp . Add ( it . second , temp ) ; else mp [ it . second ] = temp ; } int It = 0 ; foreach ( int key in mp . Keys ) { if ( mp [ key ] . Count == 1 ) { It = key ; } } int adjacent = It ; res . Add ( It ) ; visited . Add ( It , true ) ; while ( res . Count != A . Count + 1 ) { foreach ( int elements in mp [ adjacent ] ) { if ( ! visited . ContainsKey ( elements ) ) { res . Add ( elements ) ; visited . Add ( elements , true ) ; adjacent = elements ; } } } foreach ( int val in res ) { Console . Write ( val + " ▁ " ) ; } } static public void Main ( ) { List < Pair > A = new List < Pair > ( ) ; A . Add ( new Pair ( 5 , 1 ) ) ; A . Add ( new Pair ( 3 , 4 ) ) ; A . Add ( new Pair ( 3 , 5 ) ) ; find_original_array ( A ) ; } }