From 5fbb5fdc2ca45d5e210f4f7a043a9da52ca1a1d3 Mon Sep 17 00:00:00 2001 From: David Gao Date: Sat, 13 Jan 2024 20:44:21 -0500 Subject: [PATCH] =?UTF-8?q?0322.=E9=87=8D=E6=96=B0=E5=AE=89=E6=8E=92?= =?UTF-8?q?=E8=A1=8C=E7=A8=8B.md=20=E8=A7=A3=E5=86=B3python=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=9D=97=20=E5=9B=9E=E6=BA=AF=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E5=AD=97=E5=85=B8=E6=96=B9=E6=B3=95=E4=BB=A3=E7=A0=81=E8=B6=85?= =?UTF-8?q?=E6=97=B6=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 49 +++++++++++++++-------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 1473ed05..036cfc51 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -449,34 +449,37 @@ class Solution: ``` 回溯 使用字典 ```python -from collections import defaultdict - class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: - targets = defaultdict(list) # 构建机场字典 - for ticket in tickets: - targets[ticket[0]].append(ticket[1]) - for airport in targets: - targets[airport].sort() # 对目的地列表进行排序 + self.adj = {} - path = ["JFK"] # 起始机场为"JFK" - self.backtracking(targets, path, len(tickets)) - return path + # sort by the destination alphabetically + # 根据航班每一站的重点字母顺序排序 + tickets.sort(key=lambda x:x[1]) - def backtracking(self, targets, path, ticketNum): - if len(path) == ticketNum + 1: - return True # 找到有效行程 + # get all possible connection for each destination + # 罗列每一站的下一个可选项 + for u,v in tickets: + if u in self.adj: self.adj[u].append(v) + else: self.adj[u] = [v] - airport = path[-1] # 当前机场 - destinations = targets[airport] # 当前机场可以到达的目的地列表 - for i, dest in enumerate(destinations): - targets[airport].pop(i) # 标记已使用的机票 - path.append(dest) # 添加目的地到路径 - if self.backtracking(targets, path, ticketNum): - return True # 找到有效行程 - targets[airport].insert(i, dest) # 回溯,恢复机票 - path.pop() # 移除目的地 - return False # 没有找到有效行程 + # 从JFK出发 + self.result = [] + self.dfs("JFK") # start with JFK + + return self.result[::-1] # reverse to get the result + + def dfs(self, s): + # if depart city has flight and the flight can go to another city + while s in self.adj and len(self.adj[s]) > 0: + # 找到s能到哪里,选能到的第一个机场 + v = self.adj[s][0] # we go to the 1 choice of the city + # 在之后的可选项机场中去掉这个机场 + self.adj[s].pop(0) # get rid of this choice since we used it + # 从当前的新出发点开始 + self.dfs(v) # we start from the new airport + + self.result.append(s) # after append, it will back track to last node, thus the result list is in reversed order ``` 回溯 使用字典 逆序