332 Reconstruct Itinerary
from collections import defaultdict
class Solution:
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
if not tickets or not tickets[0]:
return []
# build representative graph
g = defaultdict(list)
for _to, _from in tickets:
g[_to].append(_from)
# now sort to create smallest
# lexicographical itinerary
for _to, _ in g.items():
g[_to].sort()
# maintain an index where the eularian path
# left off
left_off = {}
for _to, _from in tickets:
left_off[_to] = 0
left_off[_from] = 0
itinerary = []
s = ['JFK']
# now find the eularian path
while s:
top = s[-1]
g_index = left_off[top]
g_list = g[top]
if g_index < len(g_list):
s.append(g_list[g_index])
left_off[top] = g_index + 1
else:
itinerary.append(top)
s.pop()
return list(reversed(itinerary))Last updated