1. 程式人生 > >[LeetCode] 332. Reconstruct Itinerary Java

[LeetCode] 332. Reconstruct Itinerary Java

pair sem add 最小路徑 深度 pub logs who 如果

題目

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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. 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<String,PriorityQueue<String>>保存每個點及其鄰節點,然後使用深度遍歷,第一次得到的結果便是答案(因為每次都是用的最小路徑)。 另外一種方法是每次找到終點,然後刪除該點繼續查找下一個終點,最後得到的結果反轉即可。

實際上,這道題目是計算最小的歐拉路徑。通過分析可以知道: 如果一個有向圖,存在歐拉路徑(不是歐拉回路),那麽圖中的點最多只可能有兩個點:degree(入)!=degree(出),並且這兩個點,一個入度>出度,一個入度<出度;也有可能所有點degree(入)==degree(出),則存在歐拉回路 很明顯,既然題目保證存在歐拉路徑,那麽JFK就是那個入度<出度的點,並且存在一個點入度>出度;或者所有點入度==出度 貪心法:從JFK開始,每次選取最小路徑走,如果走不下去,只有可能遇到了終結點PP(那個入度>出度的點),這樣就形成了從JFK到PP的主路徑。剩下沒走的邊只有可能形成環,只要將環並入到主路徑上就完成了最小歐拉路徑的搜索!!

代碼:

public class Solution {
    Map<String, PriorityQueue<String>>  map= new HashMap<>();
    List<String> res = new ArrayList<>();

    public List<String> findItinerary(String[][] tickets) {
        for(String[] ticket:tickets){
            map.computeIfAbsent(ticket[0],k->new PriorityQueue<>()).add(ticket[1]);
        }
        dfs("JFK");
        Collections.reverse(res);
        return res;
    }

    public void dfs(String node){
        PriorityQueue<String> priorityQueue = map.get(node);
        while(priorityQueue!=null&&!priorityQueue.isEmpty())
            dfs(priorityQueue.poll());
        res.add(node);
    }
}

[LeetCode] 332. Reconstruct Itinerary Java