Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Problem of the day

You are given a matrix of flight 'TICKETS', where the 'i'th row represents 'i’th flight ticket. 'TICKETS'[i] = [SOURCE, DESTINATION] represents that there is a one-way flight starting from the city 'SOURCE' and ending at city 'DESTINATION'. All the flight tickets belong to a man who is initially in city "DEL".

You are supposed to reconstruct the journey satisfying the following conditions:

1. He should begin his journey from “DEL”.

2. He should use all the tickets and complete the journey.

3. He must use all the tickets only once.

```
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.
```

Detailed explanation

```
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].
```

```
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.

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
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
```

```
1
3
DEL KUL
DEL NRT
NRT DEL
```

```
DEL NRT DEL KUL
```

```
In test case 1, there are three flight tickets.
Source - Destination
DEL - KUL
DEL - NRT
NRT - DEL
In order to satisfy all the conditions, he should start from “DEL”, as per the problem statement, use ticket 2, go to “NRT”. Then come back to “DEL” using ticket 3. And then go to “KUL” using ticket 1. So the Itinerary which is possible in this case is DEL -> NRT -> DEL -> KUL.
```

```
1
2
DEL ATL
ATL DEL
```

```
DEL ATL DEL
```

```
In test case 1, there are two flight tickets.
Source - Destination
DEL - ATL
ATL - DEL
In order to satisfy all the conditions, he should start from “DEL”, as per the problem statement, use ticket 1, go to “ATL”. Then come back to “DEL” using ticket 2. So the Itinerary which is possible in this case is DEL -> ATL -> DEL.
```