332. Reconstruct Itinerary

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

这道题给我们一堆飞机票,让我们建立一个行程单,如果有多种方法,取其中字母顺序小的那种方法。这道题的本质是有向图的遍历问题,那么LeetCode关于有向图的题只有两道Course ScheduleCourse Schedule II,而那两道是关于有向图的顶点的遍历的,而本题是关于有向图的边的遍历。每张机票都是有向图的一条边,我们需要找出一条经过所有边的路径,那么DFS不是我们的不二选择。先来看递归的结果,我们首先把图建立起来,通过邻接链表来建立。由于题目要求解法按字母顺序小的,那么我们考虑用heap,可以自动排序。等我们图建立好了以后,从节点JFK开始遍历,只要当前节点映射的heap里有节点,我们取出这个节点,将其在heap里删掉,然后继续递归遍历这个节点,由于题目中限定了一定会有解,那么等图中所有的heap中都没有节点的时候,我们把当前节点存入结果中,然后再一层层回溯回去,将当前节点都存入结果,那么最后我们结果中存的顺序和我们需要的相反的,我们最后再翻转一下即可,参见代码如下

public class Solution {
    LinkedList<String> res;
    Map<String, PriorityQueue<String>> mp;

    public List<String> findItinerary(String[][] tickets) {
        if (tickets==null || tickets.length==0) return new LinkedList<String>();
        res = new LinkedList<String>();
        mp = new HashMap<String, PriorityQueue<String>>();
        for (String[] ticket : tickets) {
            if (!mp.containsKey(ticket[0])) {
                mp.put(ticket[0], new PriorityQueue<String>());
            }
            mp.get(ticket[0]).offer(ticket[1]);
        }
        dfs("JFK");
        return res;
    }

    public void dfs(String cur) {
        while (mp.containsKey(cur) && !mp.get(cur).isEmpty()) {
            dfs(mp.get(cur).poll());
        }
        res.addFirst(cur);
    }
}

  

注释: 欧拉回路,Hierholzer算法
Reconstruct Itinerary
这题不是简单的 DFS,而是欧拉回路。。。因为我们一定可以从 JFK 出发并回到 JFK ,则 JFK 一定是图中
的奇点,有奇数的 in+out degrees;
Greedy DFS, building the route backwards when retreating.
这题其实和我之前用 DFS 处理 topological sort 的代码非常像,主要区别在于存
graph 的方式不同,这里是一个 String 直接连着对应的 next nodes,而且形式是
min heap:
原题给的是 edges,所以图是自己用 hashmap 建的。
min heap 可以自动保证先访问 lexicographical
order 较小的;
同时 poll 出来的 node 自动删除,免去了用 List 的话
要先 collections.sort 再 remove 的麻烦。
这种以 “edge” 为重心的算法多靠 heap,比如
dijkstra

  

Hierholzer 算法: 
另一种计算欧拉回路的算法是 Hierholzer 算法。这种算法是基于这样的观察: 
 
在手动寻找欧拉路的时候,我们从点 4 开始,一笔划到达了点 5,形成路径 4-5-2-3-6-5。此时我们把这条路径去掉,则剩下三条边,2-4-1-2 可以一笔画出。

这两条路径在点 2 有交接处(其实点 4 也是一样的)。那么我们可以在一笔画出红色轨迹到达点 2 的时候,一笔画出黄色轨迹,再回到点 2,把剩下的红色轨迹画完。

由于明显的出栈入栈过程,这个算法可以用 DFS 来描述。 
如果想看得更仔细一点,下面是从点 4 开始到点 5 结束的 DFS 过程,其中 + 代表入栈,- 代表出栈。 
4+ 5+ 2+ 3+ 6+ 5+ 5- 6- 3- 1+ 4+ 2+ 2- 4- 1- 2- 5- 4- 
我们把所有出栈的记录连接起来,得到 
5-6-3-2-4-1-2-5-4

时间: 2024-12-13 06:46:23

332. Reconstruct Itinerary的相关文章

leetcode 332 Reconstruct Itinerary

题目连接 https://leetcode.com/problems/reconstruct-itinerary/ Reconstruct Itinerary Description 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 belo

[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: If ther

332. Reconstruct Itinerary (leetcode)

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 ar

332. Reconstruct Itinerary --- DFS转迭代,用栈

好久没写题解了,今天做了一道图题,觉得解法很不错. 题目: 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 beg

【LeetCode】Reconstruct Itinerary(332)

1. Description 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. No

Leetcode: Reconstruct Itinerary

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 ar

[LeetCode] Reconstruct Itinerary 重建行程单

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 ar

Reconstruct Itinerary

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 ar

【Leetcode】Reconstruct Itinerary

题目链接: https://leetcode.com/problems/reconstruct-itinerary/ 题目: 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