Reconstruct Itinerary in C++


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

So if the input is like [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]], then the output will be ["JFK", "MUC", "LHR", "SFO", "SJC"].

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(“JFK”) as this is the first airport

  • reverse the list ret and return

Example(C++)

Let us see the following implementation to get a 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("JFK");
      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 = {{"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"}};
   print_vector(ob.findItinerary(v));
}

Input

[["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]

Output

[JFK, MUC, LHR, SFO, SJC, ]

Updated on: 02-May-2020

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements