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

思路
这个题是一个图的题目

  1. 首先建立图,利用hashmap和priorityqueue,因为题目要求字母最小序列,那么用pq,可以利用string自己本身的compareTo功能,进行排序.
  2. 从JFK开始dfs,每次找到终点,那么都要从PriorityQueue里面弹出来(每次访问过的就会从hashmap中弹出来),然后反向加回来(每一次都加在list的最前面),在dfs的最后加过来就是正的顺序。
class Solution {
    public List<String> findItinerary(String[][] tickets) {
        List<String> path = new ArrayList<String>();
        
        if (tickets == null || tickets.length == 0) {
            return path;
        }
        
        //1. reconstruct the graph based on priorityQueue
        HashMap<String, PriorityQueue<String>> mapping = new HashMap<>();
        
        for (int i = 0; i < tickets.length; i++) {
            if (!mapping.containsKey(tickets[i][0])) {
                //PriorityQueue<String> queue = new PriorityQueue<String>(); 
                mapping.put(tickets[i][0], new PriorityQueue<String>());
            }
            mapping.get(tickets[i][0]).offer(tickets[i][1]);
        }
        
        //2. DFS to find all path
        findPath(mapping, path, "JFK");
        return path;
    } 
    
    public void findPath(HashMap<String, PriorityQueue<String>> mapping, List<String> path, String startWord) {
        PriorityQueue<String> queue = mapping.get(startWord);
        while (queue != null && !queue.isEmpty()) {
            findPath(mapping, path, queue.poll());
        }
        path.add(0, startWord);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容