[LC] 332. Reconstruct Itinerary
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"]
class Solution { public List<String> findItinerary(List<List<String>> tickets) { Map<String, PriorityQueue<String>> map = new HashMap<>(); for (int i = 0; i < tickets.size(); i++) { List<String> curList = tickets.get(i); if (!map.containsKey(curList.get(0))) { map.put(curList.get(0), new PriorityQueue<>()); } map.get(curList.get(0)).add(curList.get(1)); } List<String> res = new LinkedList<>(); find("JFK", map, res); return res; } private void find(String start, Map<String, PriorityQueue<String>> map, List<String> res) { while (map.containsKey(start) && !map.get(start).isEmpty()) { String cur = map.get(start).poll(); find(cur, map, res); } res.add(0, start); } }