The original title link is here: 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 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.
Exercises
Build directed graph with these ticket as edge. In order to guarantee the alphabetical order, Priorityqueue was used. Then do DFS.
Time Complexity:o (n+e). Space:o (n+e).
AC Java:
1 Public classSolution {2map<string, priorityqueue<string>> graph =NewHashmap<string, priorityqueue<string>>();3 PublicList<string>finditinerary (string[][] tickets) {4list<string> res =NewLinkedlist<string>();5 if(Tickets = =NULL|| Tickets.length = = 0 | | Tickets[0].length = = 0){6 returnRes;7 }8 9 for(String [] edge:tickets) {Ten if(!graph.containskey (edge[0])){ OneGraph.put (Edge[0],NewPriorityqueue<string>()); A } -Graph.get (Edge[0]). Add (edge[1]); - } the -DFS ("JFK", res); - returnRes; - } + - Private voidDFS (String s, list<string>Res) { + while(Graph.containskey (s) &&!Graph.get (s). IsEmpty ()) { A Dfs (Graph.get (s). Poll (), res); at } -Res.add (0, s); - } -}
Leetcode Reconstruct itinerary