332. Reconstruct Itinerary

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:

  1. 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"].

  2. All airports are represented by three capital letters (IATA code).

  3. You may assume all tickets form at least one valid itinerary.

Example 1:

Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
             But it is larger in lexical order.

解题要点:

大神说了 “Just Eulerian path. Greedy DFS, building the route backwards when retreating.”

Python: (Recursive)

class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        res = []
        mydict = collections.defaultdict(list)
        for f, t in sorted(tickets)[::-1]:
            mydict[f].append(t) # mydict[f] += t,
        
        def visit(airport):
            while mydict[airport]:
                visit(mydict[airport].pop())
            res.append(airport)
        visit("JFK")
        return res[::-1]

Iterative:

class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        
        mydict = collections.defaultdict(list)
        for f, t in sorted(tickets)[::-1]:
            mydict[f].append(t)                       # mydict[f] += t,
        
        res = []
        stack = ["JFK"]
        while stack:
            while mydict[stack[-1]]:
                stack.append(mydict[stack[-1]].pop()) # stack += mydict[stack[-1]].pop(),            
            res.append(stack.pop())                   # route += stack.pop(),
        return res[::-1]

以上解法都贼拉快。

Last updated

Was this helpful?