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 {
   public:
   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];
         graph[u].insert(v);
      }
      visit("Chennai");
      reverse(ret.begin(), ret.end());
      return ret;
   }
   void visit(string airport){
      while(graph[airport].size()){
         string x = *(graph[airport].begin());
         graph[airport].erase(graph[airport].begin());
         visit(x);
      }
      ret.push_back(airport);
   }
};
main(){
   Solution ob;
   vector<vector<string>> v = {{"Mumbai", "Kolkata"}, {"Chennai", "Mumbai"}, {"Delhi", "Bangalore"}, {"Kolkata", "Delhi"}};
   print_vector(ob.findItinerary(v));
}

Input

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

Output

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

Updated on: 25-Aug-2020

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements