LeetCode 332
因为给的这个题目是确保有解的,这样的话,从起点开始肯定是可以到达每个点,并且肯定只有一个终点。通过DFS的方式,我们可以找到这个终点,一旦不能再去其他的地方,我们可以把终点加入到我们的path里面进去,同时从图上去掉终点。回退到进入终点的点,看是否还能去其他地方,如果不能,也可以加入到这个path。如果中间点还可以去其他的地方,那么在加入path的时候,需要插入到去终点之前的位置。
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
#保证字母序排序
tickets.sort(key=lambda x:x[1])
#建图
graph = collections.defaultdict(list)
for u, v in tickets:
graph[u].append(v)
#DFS
itinerary, stack = [], [("JFK")]
while stack:
current = stack[-1]
if current in graph and len(graph[current]) > 0:
stack.append(graph[current].pop(0))
else:
itinerary.append(stack.pop())
return itinerary[::-1]