LeetCode: Reconstruct Itinerary

/**
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:
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.
*/

/**
Solution:
-add the src, dest pair in hash whose key is src and value is PriorityQueue
-in while loop traverse through the first src JFK until the final destination is found
-remove the final destination from the PriorityQueue of the map it belongs to
-in the loop get the dest from a place and use the dest as new src
-repeat the process until the destination of all places are polled out from the PriorityQueue
-as we find the final destination first, the other results are added to the front of the result to make the itinerary valid

DFS until the arrival of the arrival of the pq, and then add the last city, addFirst.
All the airports are vertices and tickets are directed edges. Then all these tickets form a directed graph

*/
public class ReconstructItinerary{
public List<String> findItinerary(String[][] tickets) {
        LinkedList<String> result = new LinkedList<>();
        if (tickets == null || tickets.length == 0) {
            return result;
        }
        HashMap<String, PriorityQueue<String>> map = new HashMap<>();
        for (String[] ticket : tickets) {
            map.putIfAbsent(ticket[0], new PriorityQueue<>());
            map.get(ticket[0]).add(ticket[1]);
        }
        dfs(result, map, "JFK");
        return result;
    }

    private void dfs(LinkedList<String> result, HashMap<String, PriorityQueue<String>> map, String current) {
        while (map.containsKey(current) && !map.get(current).isEmpty()) {
            dfs(result, map, map.get(current).poll());         
        }
        result.addFirst(current);
    }
}

No comments:

Post a Comment