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 fromJFK. 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.
思路:
这个题是一个图的题目
- 首先建立图,利用hashmap和priorityqueue,因为题目要求字母最小序列,那么用pq,可以利用string自己本身的compareTo功能,进行排序.
- 从JFK开始dfs,每次找到终点,那么都要从PriorityQueue里面弹出来(每次访问过的就会从hashmap中弹出来),然后反向加回来(每一次都加在list的最前面),在dfs的最后加过来就是正的顺序。
class Solution {
public List<String> findItinerary(String[][] tickets) {
List<String> path = new ArrayList<String>();
if (tickets == null || tickets.length == 0) {
return path;
}
//1. reconstruct the graph based on priorityQueue
HashMap<String, PriorityQueue<String>> mapping = new HashMap<>();
for (int i = 0; i < tickets.length; i++) {
if (!mapping.containsKey(tickets[i][0])) {
//PriorityQueue<String> queue = new PriorityQueue<String>();
mapping.put(tickets[i][0], new PriorityQueue<String>());
}
mapping.get(tickets[i][0]).offer(tickets[i][1]);
}
//2. DFS to find all path
findPath(mapping, path, "JFK");
return path;
}
public void findPath(HashMap<String, PriorityQueue<String>> mapping, List<String> path, String startWord) {
PriorityQueue<String> queue = mapping.get(startWord);
while (queue != null && !queue.isEmpty()) {
findPath(mapping, path, queue.poll());
}
path.add(0, startWord);
}
}