332. Reconstruct Itinerary

Medium
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.

这道题看的答案,题目要求是根据航班的from...to...组合来重建行程。其实所有的航班构成了一个有向图,要求求出一个一笔画出从起点到终点的航线。这道题答案说是 Hierholzer’s algorithm to find a Eulerian path,但我不太清楚这个,直接看解答也是看得懂的。

首先用hashMap构建邻接表,每一个出发机场对应一个PriorityQueue, 里面的String默认是按照lexical order排序,所以我们每次poll()出来的都是按照字母顺序的。helper function里先得到对应出发机场的目的地,一直对poll()出来的目的地call helper function,知道出发机场对应的PriorityQueue被取空。

同时要注意,每次call helper function,都会加上当前的str到res里面。但要用LinkedList的addFirst()这个方法. 画出递归树可以看出原因:

332. Reconstruct Itinerary_第1张图片
WechatIMG71.jpeg
class Solution {
    HashMap> maps = new HashMap<>();
    LinkedList res = new LinkedList<>();
    public List findItinerary(String[][] tickets) { 
        for (String[] ticket : tickets){
            if (!maps.containsKey(ticket[0])){
                PriorityQueue q = new PriorityQueue<>();
                maps.put(ticket[0], q);
            }
            maps.get(ticket[0]).offer(ticket[1]);
        }
        helper("JFK");
        return res;
    }
    private void helper(String str){
        PriorityQueue neighbors = maps.get(str);
        while (neighbors != null && !neighbors.isEmpty()){
            helper(neighbors.poll());
        }
        res.addFirst(str);
    }
}

你可能感兴趣的:(332. Reconstruct Itinerary)