332. Reconstruct Itinerary
Hard
Problem:
Input: tickets = [["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.Solution:
Failed Code
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
result = []
visit = []
# Smaller lexical order
def take_second(elem):
return elem[1]
sorted_tickets = sorted(tickets, key=take_second)
def dfs(index, path):
if index == len(sorted_tickets):
result.append(path)
return
for ticket in sorted_tickets:
if ticket[0] == path[-1] and ticket not in visit:
visit.append(ticket)
dfs(index + 1, path + [ticket[1]])
dfs(0, ["JFK"])
return result[0] if len(result) > 0 else resultModified Code (Stack)
DFS (Queue)
Iteration
Last updated