leetcode solution: Reconstruct Itinerary (332)

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.

解法1:建图 + DFS

首先是建图的思想,这题看起来就要用DFS,可是没有图可以操作,对于这类的问题要想到用一个Hashmap来构造图的边的关系。
这里有一个小的trick是用到了PriorityQueue, 因为最后的结果是要排序后较小的,那么我们构建hashmap的时候就要把每一个start对应的destination排好序,我们就可以用PQ来存储。
而题目有一个隐含的条件就是一定有解,那么如果我们在搜索碰到一个没有对应destination的城市的时候,他一定是要求的最后一个string。
所以我们在写DFS的时候,要把res.add(cur)放在while语句之后。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution {
public List<String> findItinerary(String[][] tickets) {
// Construct the graph, using HashMap
HashMap<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>();
for (String[] pair: tickets) {
if (map.containsKey(pair[0])) {
map.get(pair[0]).add(pair[1]);
} else {
map.put(pair[0], new PriorityQueue<String>());
map.get(pair[0]).add(pair[1]);
}
}
// DFS the map and construct the itinerary
List<String> res = new ArrayList<String>();
dfs(map, "JFK", res);
Collections.reverse(res);
return res;
}
void dfs(HashMap<String, PriorityQueue<String>> map, String cur, List<String> res) {
while (map.containsKey(cur) && !map.get(cur).isEmpty()) {
dfs(map, map.get(cur).poll(), res);
}
res.add(cur);
}
}