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. 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. 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.
将上述的问题用图的形式表示出来
对于Example1,表示为:
可以看到只有一条可以从JFK一次用光全部Tickets的方案
对于Example2,表示为:
可以看到,3个可能的路径中,1??最小,符合要求。
根据题目的理解,分析找到路径1的过程:
我们从JFK出发:
考虑下面这种情况:
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
// 初始化Map<出发点,对应可抵达队列>
Map<String, Queue<String>> map = new HashMap<>();
for (List<String> ticket : tickets) {
if (!map.containsKey(ticket.get(0))) {
map.put(ticket.get(0), new PriorityQueue<String>());
}
map.get(ticket.get(0)).add(ticket.get(1));
}
String beginWith = "JFK";
List<String> result = new ArrayList<>();
dfs(beginWith, map, result);
// int begin = 0;
// int end = postorder.size() - 1;
// while (begin < end) {
// String temp = postorder.get(begin);
// postorder.set(begin, postorder.get(end));
// postorder.set(end, temp);
// begin++;
// end--;
// }
return result;
}
private void dfs(String beginWith, Map<String, Queue<String>> map, List<String> postorder) {
// if (!map.containsKey(beginWith) || map.get(beginWith).isEmpty()) {
// postorder.add(0, beginWith);
// return;
// }
// while(!map.get(beginWith).isEmpty()) {
// dfs(map.get(beginWith).poll(), map, postorder);
// }
// postorder.add(0, beginWith);
// 优化后的代码
if (map.containsKey(beginWith)) { // 如果beginWith是一个出发点,对其进行后续遍历
while(!map.get(beginWith).isEmpty()) { // 多叉树的后续遍历模版
dfs(map.get(beginWith).poll(), map, postorder); // 使用queue的poll()方法,将已经访问过的节点从可选列表中弹出
}
}
// 访问完beginWith的所有children后,加入beginWith
// 采用了add(index, element)不需要后续在反转结果
postorder.add(0, beginWith);
}
}
原文:https://www.cnblogs.com/isguoqiang/p/11605920.html