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:
["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].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); } }
[LC] 332. Reconstruct Itinerary
原文:https://www.cnblogs.com/xuanlu/p/13058426.html