# Reconstruct Itinerary

Posted: 22 Mar, 2021
Difficulty: Moderate

## PROBLEM STATEMENT

#### 3. He must use all the tickets only once.

##### Note:
``````1. Journey means the order in which the cities will be visited.

2. The given tickets have at least one itinerary.

3. If multiple valid itineraries are possible, then return the itinerary that is a lexicographically smallest itinerary.
``````
##### Input Format:
``````The first line of input contains an integer ‘T’, denoting the number of test cases.

The first line of each test case contains integer ‘N’, which denotes the number of rows of the matrix ‘TICKET’.

The next 'N' lines contain two strings, ‘TICKET’[i][0] and ‘TICKET’[i][1], denoting that there is a flight from ‘TICKET’[i][0] to ‘TICKET’[i][1].
``````
##### Output Format:
``````The output of each test case contains the order of cities that he should visit to satisfy the given conditions separated by space.
``````

The output of each test case is printed in a separate line.

##### Note:
``````You do not need to print anything, it has already been taken care of. Just implement the given function.
``````
##### Constraints:
``````1 <= T <= 50
1 <= N <= 20000
0 <= M <= 20000
TICKET[i][0] != TICKET[i][1], for any valid 'i'.

Where 'M' denotes the size of the given matrix ‘TICKET’.

Time Limit: 1 sec
``````
Approach 1

The idea is to represent the given tickets as a directed graph. As all the tickets form a valid route, it means the graph is a connected graph.

To construct the graph, we can use a hashMap in which the key will be a string and the value will be a list of strings. The key will represent the source and the values will represent the destination.

As we have to make the itinerary in lexicographical order. It means we have to choose the tickets in such a way that it is in sorted order. For this, we can use a multi-set list for storing the values of the hashMap.

For finding the itinerary, we will use Depth-first Search.

The steps are as follows:

1. Make a directed graph named ‘GRAPH’ from the given matrix ‘ticket’.
• Declare a hashMap with key as string and value as a multiset of strings.
• Iterate over all the tickets:
• Let the first element of the current row be denoted by ‘a’ and the second element of the current row be denoted by ‘b’.
• Append ‘b’ at the end of ‘GRAPH[a]'.