Topic Links:
https://leetcode.com/problems/reconstruct-itinerary/
Topic:
Given A list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the Itinera Ry in order. All of the tickets belong to a mans who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If There is multiple valid itineraries, you should return the itinerary that have the smallest lexical order when read as A single string. For example, the itinerary ["JFK", "LGA"] have a smaller lexical order than ["JFK", "LGB"].
All airports is represented by three capital letters (IATA code).
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's larger in lexical order.
Ideas:
The essence is to seek Oraton road, adopt Hierholzer algorithm.
Saves each edge with a priority queue (the string default dictionary order), creating an adjacency table.
DFS, which accesses neighbor nodes in dictionary order, accesses the edge while deleting the
Algorithm:
hashmap<String, priorityqueue<String>> maps =Newhashmap<String, priorityqueue<String>> (); linkedlist<String> res =Newlinkedlist<String> (); Public list<String> Finditinerary (String[] tickets) { for(int i =0; i < tickets.length; i++) {if(!maps.containskey (tickets[i][0]) {priorityqueue<String> P =Newpriorityqueue<String> (); Maps.put (tickets[i][0], p); } maps.get (tickets[i][0]). Offer (tickets[i][1]); } DSP ("JFK");returnRes } publicvoidDspStrings) {priorityqueue<String> neibors = Maps.get (s); while(Neibors! =NULL&&!neibors.isempty ()) {DSP (Neibors.poll ());//Access an edge to delete the edge} res.addfirst (s); }
"Leetcode" reconstruct itinerary