Given a list of airline tickets represented by pairs of departure and arrival airports [from, to]
, reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK
. Thus, the itinerary must begin with JFK
.
Note:
- If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary
["JFK", "LGA"]
has a smaller lexical order than["JFK", "LGB"]
. - All airports are represented by three capital letters (IATA code).
- You may assume all tickets form at least one valid itinerary.
Example 1:
Input:
[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output:["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input:
[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output:["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is["JFK","SFO","ATL","JFK","ATL","SFO"]
. But it is larger in lexical order.
Approach #1: C++.
class Solution { public: vector<string> findItinerary(vector<pair<string, string>>& tickets) { int size = tickets.size(); sort(tickets.begin(), tickets.end()); unordered_map<string, vector<string>> m; for (int i = 0; i < size; ++i) m[tickets[i].first].push_back(tickets[i].second); vector<string> ans; string start = "JFK"; string temp; int times = size; ans.push_back(start); while(times--) { temp = m[start][0]; m[start].erase(m[start].begin()); ans.push_back(temp); start = temp; } return ans; } };
Approach #2: Java.
class Solution { public List<String> findItinerary(String[][] tickets) { for (String[] ticket : tickets) targets.computeIfAbsent(ticket[0], k->new PriorityQueue()).add(ticket[1]); visit("JFK"); return route; } Map<String, PriorityQueue<String>> targets = new HashMap<>(); List<String> route = new LinkedList(); void visit(String airport) { while (targets.containsKey(airport) && !targets.get(airport).isEmpty()) { visit(targets.get(airport).poll()); } route.add(0, airport); } }
Approach #3: Python.
class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ targets = collections.defaultdict(list) for a, b in sorted(tickets)[::-1]: targets[a] += b, route, stack = [], ['JFK'] while stack: while targets[stack[-1]]: stack += targets[stack[-1]].pop(), route += stack.pop(), return route[::-1]