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 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 have
["JFK", "LGA"]
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.
Analysis:
Use DFS. Termination:when all tickets is used. Invalid:if Haven ' t used all ticket, but reach some city without any outgoing tickets.
Solution:
1 Public classSolution {2 Public classTicketgroup {3List<string>outlist;4 Boolean[] visited;5 6 PublicTicketgroup (String firstoutcity) {7Outlist =NewArraylist<string>();8 Outlist.add (firstoutcity);9 } Ten } One A PublicList<string>finditinerary (string[][] tickets) { -List<string> reslist =NewArraylist<string>(); - if(Tickets.length = = 0)returnreslist; the -hashmap<string,ticketgroup> graph =NewHashmap<string,ticketgroup>(); - for(string[] ticket:tickets) { - if(Graph.containskey (ticket[0])){ +Graph.get (Ticket[0]). Outlist.add (ticket[1]); -}Else { +Ticketgroup Group =NewTicketgroup (ticket[1]); AGraph.put (ticket[0],group); at } - } - for(Ticketgroup group:graph.values ()) { - Collections.sort (group.outlist); -group.visited =New Boolean[Group.outList.size ()]; - } in -Reslist.add ("JFK"); toFinditineraryrecur ("JFK", graph,reslist,tickets.length+1); + returnreslist; - } the * Public BooleanFinditineraryrecur (String cur, hashmap<string,ticketgroup> graph, list<string> reslist,intmaxlen) { $ if(reslist.size () = =maxlen)Panax Notoginseng return true; - the if(!graph.containskey (cur))return false; + BooleanAvailable =false; ATicketgroup Curgroup =graph.get (cur); the for(Booleanvisit:curGroup.visited) + if(!visit) { -Available =true; $ Break; $ } - if(!available)return false; - the for(inti=0;i<curgroup.visited.length;i++){ - if(!Curgroup.visited[i]) {WuyiCurgroup.visited[i] =true; the Reslist.add (CurGroup.outList.get (i)); - if(Finditineraryrecur (CurGroup.outList.get (i), Graph,reslist,maxlen)) { Wu return true; - } AboutReslist.remove (Reslist.size ()-1); $Curgroup.visited[i] =false; - } - } - return false; A } +}
Leetcode-reconstruct Itinerary