You are given a list of airline tickets
where tickets[i] = [fromi, toi]
represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from "JFK"
, thus, the itinerary must begin with "JFK"
. 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"]
.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
Example 1:
Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]
Example 2:
Input: tickets = [["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.
Constraints:
1 <= tickets.length <= 300
tickets[i].length == 2
fromi.length == 3
toi.length == 3
-
and consist of uppercase English letters. - $
from_i$ != $to_i$
題目給定一個整數矩陣 tickets , 其中每個 entry ticket[i] = [$location_1$,
要求寫一個演算法
找出從 “JFK” 出發按照給定的 tickets 以及地點字母排序 走訪完所有 path 的一個可行順序
首先是這次的 path 是有順序的
所以關鍵是要透過 tickets 做出 adjacency list
然後這些 adjacency list 需要按照字母順序排列
一個可行的作法是先把 tickets 先做字母排序
然後在照順序做 adjacency list
然後依序從 “JFK” 做 DFS
然後每次經過一個地點 就把原本的 adjacency list 的 path消去一個
import java.util.*;
public class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
HashMap<String, PriorityQueue<String>> map = new HashMap<>();
List<String> result = new ArrayList<>();
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));
}
dfs("JFK", map, result);
return result;
}
public static void dfs(String airPort, HashMap<String, PriorityQueue<String>> map, List<String> result) {
while(map.containsKey(airPort) && !map.get(airPort).isEmpty()) {
PriorityQueue<String> toAirports = map.get(airPort);
String toAirport = toAirports.poll();
dfs(toAirport, map, result);
}
result.add(0, airPort);
}
}
- 理解如何達成有序的找到 Location
- 對 DFS 需要去理解
- 需要知道如何找到鄰近的 Location
- 建立 adjacency list 時需要透過 sort 去處理