【Leetcode】python - [332] Reconstruct Itinerary 個人解法筆記

題目出處

332. Reconstruct Itinerary

難度

Hard

個人範例程式碼

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        graph = self.build_graph(tickets)
        self.ans = []
        self.dfs(graph, 'JFK')

        return self.ans[::-1]

    def build_graph(self, tickets):
        graph = collections.defaultdict(list)
        for _from, _to in tickets:
            graph[_from].append(_to)

        for _from in graph:
            graph[_from].sort(reverse = True)
            # dfs get reverse lexical order (since we get ans from end to start)           

        return graph

    def dfs(self, graph, _from):
        # end of recursion, when find no route
        while graph[_from]:
            # define and split
            self.dfs(graph, graph[_from].pop())

        # append ans, from end to start
        self.ans.append(_from)

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

這題要同時考到建構出一個 graph,
並 dfs 找尋路徑。

(這題還沒有靠自己完全寫出來,目前先參考下方 reference 進行仿寫)

反向建立 _to 順序,正向 dfs 搜尋

因為題目希望最後我們能夠照字母大小排序,而我們建立 graph 時,
先把「名稱排序比較後面的,放到前面順位」,
這樣「dfs 搜尋時,就會先 pop()」,
而最後「我們在把 from end to start 的路徑倒過來」。

input handling

x

Boundary conditions

在 graph 與 bfs 中控制搜尋範圍,搜尋完全部 node 就正常結束。
(沒有全部搜尋完,就沒有結果)

Reference