[LeetCode] 332. Reconstruct Itinerary Java

题目

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);
    }
}

 

 

 

 

 
 

 

posted @ 2017-07-28 16:56  荒野第一快递员  阅读(798)  评论(0编辑  收藏  举报