Find Itinerary from a given list of tickets in C++

Suppose we have a list of tickets represented by pairs of departure and arrival airports like [from, to], we have to find the itinerary in order. All of the tickets belong to a man who departs from Chennai. So, the itinerary must begin with Chennai.

So if the input is like [["Mumbai", " Kolkata"], ["Chennai ", " Mumbai"], ["Delhi", "Bangalore"], ["Kolkata", " Delhi"]], then the output will be ["Chennai", " Mumbai", " Kolkata", " Delhi", "Bangalore"].

To solve this, we will follow these steps −

  • Define array ret and a map called graph.

  • Define a method called visit. This will take airport name as input

  • while size of the graph[airport] is not 0

    • x := first element of graph[airport]

    • delete the first element from graph[airport]

    • call visit(x)

  • insert airport into ret

  • Now from the main method, do the following −

  • for i in range 0 to size of tickers array

    • u := tickets[i, 0], v := tickets[i, 1], insert v into graph[u]

  • visit(“Chennai”) as this is the first airport

  • reverse the list ret and return

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   cout << "]"<<endl;
class Solution {
   vector <string> ret;
   map < string, multiset <string> > graph;
   vector<string> findItinerary(vector<vector<string>>& tickets) {
      for(int i = 0; i < tickets.size(); i++){
         string u = tickets[i][0];
         string v = tickets[i][1];
      reverse(ret.begin(), ret.end());
      return ret;
   void visit(string airport){
         string x = *(graph[airport].begin());
   Solution ob;
   vector<vector<string>> v = {{"Mumbai", "Kolkata"}, {"Chennai", "Mumbai"}, {"Delhi", "Bangalore"}, {"Kolkata", "Delhi"}};


{{"Mumbai", "Kolkata"}, {"Chennai", "Mumbai"}, {"Delhi", "Bangalore"}, {"Kolkata", "Delhi"}}


[Chennai, Mumbai, Kolkata, Delhi, Bangalore, ]