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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_original_array ( vector < pair < int , int > > & A ) { unordered_map < int , vector < int > > mp ; vector < int > res ; unordered_map < int , bool > visited ; for ( auto & it : A ) { mp [ it . first ] . push_back ( it . second ) ; mp [ it . second ] . push_back ( it . first ) ; } auto it = mp . begin ( ) ; for ( ; it != mp . end ( ) ; it ++ ) { if ( it -> second . size ( ) == 1 ) { break ; } } int adjacent = it -> first ; res . push_back ( it -> first ) ; visited [ it -> first ] = true ; while ( res . size ( ) != A . size ( ) + 1 ) { for ( auto & elements : mp [ adjacent ] ) { if ( ! visited [ elements ] ) { res . push_back ( elements ) ; visited [ elements ] = true ; adjacent = elements ; } } } for ( auto it : res ) { cout << it << " ▁ " ; } } int main ( ) { vector < pair < int , int > > A = { { 5 , 1 } , { 3 , 4 } , { 3 , 5 } } ; find_original_array ( A ) ; return 0 ; }