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.
class Solution(object):
def findItinerary(self, tickets):
res = ['JFK']
dic = collections.defaultdict(list)
for flight in tickets:
dic[flight[0]] += flight[1],
#print dic
self.dfs(dic,'JFK',res,len(tickets))
return res
def dfs(self,dic,leave,res,flights):
if len(res) == flights + 1:
return res
currentDst = sorted(dic[leave]) #当前这个点对应的所有目的地
for dst in currentDst:
dic[leave].remove(dst)
res.append(dst)
valid = self.dfs(dic,dst,res,flights)
if valid:
return valid
res.pop()
dic[leave].append(dst)

本文介绍了一个算法问题,即根据给定的机票对(包含出发地和目的地)重构旅行路线。该路线必须从JFK机场开始,并且需要找到字典序最小的合法行程。通过示例展示了如何解决这一问题。

被折叠的 条评论
为什么被折叠?



