Reconstruct Itinerary (M)
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.
题意
重新安排行程,使得从”JFK”出发的航班到达所有地点,如果存在多条可行的路径,则优先走字典序较小的地点。
思路
用HashMap存储所有路径A->[B1, B2, …],并用堆来对B按照字典序排序。DFS处理:从”JFK”出发,如果当前点存在下一个可到达的点,则删除这两个点之间的边,并向下递归,处理完所有可到达的点后,将当前点加入结果序列里。DFS完成后只要将结果序列逆置即可。(逆后序遍历+贪心,类似欧拉路径)
代码实现
class Solution {public List<String> findItinerary(List<List<String>> tickets) {Map<String, Queue<String>> hash = new HashMap<>();for (List<String> list : tickets) {hash.putIfAbsent(list.get(0), new PriorityQueue<>());hash.get(list.get(0)).offer(list.get(1));}List<String> ans = new ArrayList<>();dfs(hash, ans, "JFK");Collections.reverse(ans);return ans;}private void dfs(Map<String, Queue<String>> hash, List<String> ans, String cur) {if (!hash.containsKey(cur)) {ans.add(cur);return;}Queue<String> q = hash.get(cur);while (!q.isEmpty()) {String s = q.poll();dfs(hash, ans, s);}hash.remove(cur);ans.add(cur);}}
