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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets form at least one valid itinerary.

Example 1:

  1. Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
  2. Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

  1. Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
  2. Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
  3. Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
  4. But it is larger in lexical order.

题意

重新安排行程,使得从”JFK”出发的航班到达所有地点,如果存在多条可行的路径,则优先走字典序较小的地点。

思路

用HashMap存储所有路径A->[B1, B2, …],并用堆来对B按照字典序排序。DFS处理:从”JFK”出发,如果当前点存在下一个可到达的点,则删除这两个点之间的边,并向下递归,处理完所有可到达的点后,将当前点加入结果序列里。DFS完成后只要将结果序列逆置即可。(逆后序遍历+贪心,类似欧拉路径)


代码实现

  1. class Solution {
  2. public List<String> findItinerary(List<List<String>> tickets) {
  3. Map<String, Queue<String>> hash = new HashMap<>();
  4. for (List<String> list : tickets) {
  5. hash.putIfAbsent(list.get(0), new PriorityQueue<>());
  6. hash.get(list.get(0)).offer(list.get(1));
  7. }
  8. List<String> ans = new ArrayList<>();
  9. dfs(hash, ans, "JFK");
  10. Collections.reverse(ans);
  11. return ans;
  12. }
  13. private void dfs(Map<String, Queue<String>> hash, List<String> ans, String cur) {
  14. if (!hash.containsKey(cur)) {
  15. ans.add(cur);
  16. return;
  17. }
  18. Queue<String> q = hash.get(cur);
  19. while (!q.isEmpty()) {
  20. String s = q.poll();
  21. dfs(hash, ans, s);
  22. }
  23. hash.remove(cur);
  24. ans.add(cur);
  25. }
  26. }