-
Notifications
You must be signed in to change notification settings - Fork 43
/
reconstruct-itinerary.py
78 lines (69 loc) · 2.35 KB
/
reconstruct-itinerary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/83551204
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = collections.defaultdict(list)
for frm, to in tickets:
graph[frm].append(to)
for frm, tos in graph.items():
tos.sort(reverse=True)
res = []
self.dfs(graph, "JFK", res)
return res[::-1]
def dfs(self, graph, source, res):
while graph[source]:
v = graph[source].pop()
self.dfs(graph, v, res)
res.append(source)
# V1'
# https://www.jiuzhang.com/solution/reconstruct-itinerary/#tag-highlight-lang-python
class Solution:
def findItinerary(self, tickets):
targets = collections.defaultdict(list)
for a, b in sorted(tickets)[::-1]:
targets[a] += b,
route = []
def dfs(airport):
while targets[airport]:
dfs(targets[airport].pop())
route.append(airport)
dfs('JFK')
return route[::-1]
# V2
# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets,
# ni is the number of the ticket which from is city i,
# k is the total number of cities.
# Space: O(t)
import collections
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
def route_helper(origin, ticket_cnt, graph, ans):
if ticket_cnt == 0:
return True
for i, (dest, valid) in enumerate(graph[origin]):
if valid:
graph[origin][i][1] = False
ans.append(dest)
if route_helper(dest, ticket_cnt - 1, graph, ans):
return ans
ans.pop()
graph[origin][i][1] = True
return False
graph = collections.defaultdict(list)
for ticket in tickets:
graph[ticket[0]].append([ticket[1], True])
for k in graph.keys():
graph[k].sort()
origin = "JFK"
ans = [origin]
route_helper(origin, len(tickets), graph, ans)
return ans