Description
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:
tickets
= [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]
.
Example 2:
tickets
= [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"]
.
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]
. But it is larger in lexical order.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Solution
DFS
用基础的dfs就可以解决这道题,但没有想到难住我的是用什么数据结构表示input...
由于要保证lexical order,比较直观的想法是每个toList用PriorityQueue来存储,但实现时发现递归还原PriorityQueue有坑,因为每次poll出来的都是最小值啊,没办法做到便利一个PriorityQueue。
看了些解决方案,最终采用ArrayList来存储toList,对于每个ArrayList都用Collections.sort来排一下序就好了呀。还原一个ArrayList也方便,调用add(insertIndex, element)即可。
class Solution {
public List findItinerary(String[][] tickets) {
Map> map = new HashMap<>();
for (String[] ticket : tickets) {
String from = ticket[0];
String to = ticket[1];
if (!map.containsKey(from)) {
map.put(from, new ArrayList<>());
}
map.get(from).add(to);
}
for (Map.Entry> entry : map.entrySet()) {
Collections.sort(entry.getValue()); // sort each list
}
List itinerary = new LinkedList<>();
itinerary.add("JFK");
dfsFindItinerary("JFK", map, tickets.length + 1, itinerary);
return itinerary;
}
public boolean dfsFindItinerary(
String from, Map> map
, int count, List itinerary) {
if (itinerary.size() == count) {
return true;
}
List toList = map.get(from);
if (toList == null) {
return false;
}
for (int i = 0; i < toList.size(); ++i) {
String to = toList.get(i);
toList.remove(i);
itinerary.add(to);
if (dfsFindItinerary(to, map, count, itinerary)) {
return true;
}
itinerary.remove(itinerary.size() - 1);
toList.add(i, to);
}
return false;
}
}