問題:算法
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
.api
Note:spa
["JFK", "LGA"]
has a smaller lexical order than ["JFK", "LGB"]
.Example 1:
tickets
= [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]
.code
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.orm
解決:three
① 使用Map+DFS。ip
定義:
歐拉回路:從圖的某一個頂點出發,圖中每條邊走且僅走一次,最後回到出發點;若是這樣的迴路存在,則稱之爲歐拉回路。
歐拉路徑:從圖的某一個頂點出發,圖中每條邊走且僅走一次,最後到達某一個點;若是這樣的路徑存在,則稱之爲歐拉路徑。判斷:get
無向圖歐拉回路判斷:全部頂點的度數都爲偶數。string
有向圖歐拉回路判斷:全部頂點的出度與入讀相等。it
無向圖歐拉路徑判斷: 至多有兩個頂點的度數爲奇數,其餘頂點的度數爲偶數。
有向圖歐拉路徑判斷: 至多有兩個頂點的入度和出度絕對值差1(如有兩個這樣的頂點,則必須其中一個出度大於入度,另外一個入度大於出度),其餘頂點的入度與出度相等。
全部機場都是頂點,票據是有向邊。 而後全部這些票造成一個有向圖。
由於咱們知道歐拉路徑存在,因此圖必須是歐拉。
所以,從「JFK」開始,咱們能夠應用Hierholzer算法在圖中找到歐拉路徑,這是一個有效的重構。
因爲問題要求詞法順序最小的解決方案,咱們能夠把鄰居放在一個小堆裏。 經過這種方式,咱們老是先訪問最小的鄰居。
class Solution { //10ms Map<String,PriorityQueue<String>> map = new HashMap<>(); List<String> res = new ArrayList<>(); public List<String> findItinerary(String[][] tickets) { for (String[] ticket : tickets){ if (! map.containsKey(ticket[0])){ PriorityQueue<String> queue = new PriorityQueue<>(); map.put(ticket[0],queue); } map.get(ticket[0]).offer(ticket[1]); } dfs("JFK"); return res; } public void dfs(String s){ PriorityQueue<String> queue = map.get(s); while(queue != null && ! queue.isEmpty()){ dfs(queue.poll()); } res.add(0,s); } }