"""
key is to store tickets information in default dictionary in lexical order.
and what to do when ran into destination before going through all tickets.
if encounter destination, add to result list first.
then reverse the result in the end.
"""
iterative solution
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
targets=collections.defaultdict(list)
for a , b in sorted(tickets)[::-1]:
targets[a]+=[b]
#print targets
route =[]
stack=['JFK']
while stack:
while targets[stack[-1]]:
stack.append(targets[stack[-1]].pop())
route.append(stack.pop())
return route[::-1]
recursive solution
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
targets=collections.defaultdict(list)
for a , b in sorted(tickets)[::-1]:
targets[a]+=[b]
#print targets
route =[]
def visit(airport):
while targets[airport]:
visit(targets[airport].pop())
route.append(airport)
visit('JFK')
return route[::-1]
网友评论