题目链接:
https://leetcode.com/problems/reconstruct-itinerary/
题目:
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.
思路:
实质是求欧拉通路,采用Hierholzer算法。
用优先队列(String默认字典序)保存每条边,建立邻接表。
DFS,按字典序访问邻居结点,访问的同时删除该边
算法:
HashMap<String, PriorityQueue<String>> maps = new HashMap<String, PriorityQueue<String>>();
LinkedList<String> res = new LinkedList<String>();
public List<String> findItinerary(String[][] tickets) {
for (int i = 0; i < tickets.length; i++) {
if (!maps.containsKey(tickets[i][0])) {
PriorityQueue<String> p = new PriorityQueue<String>();
maps.put(tickets[i][0], p);
}
maps.get(tickets[i][0]).offer(tickets[i][1]);
}
dsp("JFK");
return res;
}
public void dsp(String s) {
PriorityQueue<String> neibors = maps.get(s);
while (neibors != null && !neibors.isEmpty()) {
dsp(neibors.poll());// 访问某边就将该边删除
}
res.addFirst(s);
}