332. Reconstruct Itinerary (leetcode)
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:
- 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"]
. - All airports are represented by three capital letters (IATA code).
- 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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
开始以为是寻找最短路径,发现有很大区别,比如有重复节点等等。不过写到最后自己在idea上运行通过,还是花了一些时间:
其中用了异常来跳出递归,这也是在网上看到的一种跳出递归的方法,此前没有用过,学习了。
(我自己写遍历经常直接写拼音。。。这个习惯不太好,以后也会注意。。)
public class Solution { static List<String> xulie(String a,String[][] ti,int n){ ArrayList L= new ArrayList(); for(int i = 0;i<n;i++){ if(ti[i][0].equals(a)){ L.add(ti[i][1]); } } if(L.size()>1){ Collections.sort(L); } return L; } static void bianli(String a,String[][] tickets,List<String> h,Map<String,Integer> map,int n,int dp,Map<String,String> mape){ List<String> L= new ArrayList(); int p =0; L = xulie(a,tickets,n); int k =L.size(); for(int t=0;t<k;t++){ String b = L.get(t); if(map.get(b)==null){ if(dp == n-1){ h.add(b); throw new StopMsgException(); }else{ continue; } }else{ p = (int)map.get(b); if(p==0 || mape.get(a).toString().equals(b)==false){ a = b; h.add(a); map.put(a,1); mape.put(a,b); dp++; bianli(a,tickets,h,map,n,dp,mape); } } } } static void start(Map<String,Integer> map,String[][] tickets,int n){ for(int i = 0;i<n;i++){ map.put(tickets[i][0],0); } } public List<String> findItinerary(String[][] tickets) { int n = tickets.length; String a,b; int dp = 0; a="JFK"; List<String> H= new ArrayList(); H.add(a); Map map =new HashMap(); start(map,tickets,n); Map mape =new HashMap(); try { bianli(a,tickets,H,map,n,dp,mape); } catch (StopMsgException e) { return H; } return H; } static class StopMsgException extends RuntimeException { } }