Reconstruct Itinerary

题目地址:
https://leetcode.com/problems/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 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.
这里会有一些Corner Case:
[["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]。
不管怎样,保证只有一个终点。

解题思路:
这道题首先需要将输入存进map里面,然后用dfs的思想将边加入到结果里面。需要注意的是有可能会首先到达目的地,这个时候就需要将某些点加入到stack里面,最后再放进结果的list里面。


代码:

public List<String> findItinerary(String[][] tickets) {
    Map<String, PriorityQueue<String>> map = new HashMap<>();
    int edge = tickets.length;
    for(int i = 0; i <= edge - 1; i++){
        String city1 = tickets[i][0];
        if(!map.containsKey(city1)){
            map.put(city1, new PriorityQueue<>());
        }
        map.get(city1).add(tickets[i][1]);
    }
    List<String> rst = new ArrayList<>();
    Stack<String> stack = new Stack<>();
    String curr = "JFK";
    for(int i = 0; i <= edge - 1; i++){
        // this while part is roll back
        while(!map.containsKey(curr) || map.get(curr).size() == 0){
            stack.push(curr);
            curr = rst.remove(rst.size() - 1);
        }
        rst.add(curr);
        curr = map.get(curr).poll();
    }
    rst.add(curr);
    while(!stack.isEmpty()){
        rst.add(stack.pop());
    }
    return rst;
}





Comments

Popular Posts