題目出處
難度
hard
個人範例程式碼
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0 # not in wordlist
wordset = set(wordList)
this_layer = [beginWord]
visited = set([beginWord])
distance = 0
# BFS, thinking of layer
while this_layer:
distance += 1 # new bfs layer
next_layer = []
for each_word in this_layer:
if each_word == endWord: # find ans
return distance
for next_word in self.get_next_word(each_word, wordset):
if next_word in visited:
pass
else:
next_layer.append(next_word)
visited.add(next_word)
this_layer = next_layer
return 0 # not found
def get_next_word(self, each_word, wordset): # find all possible case
words = []
for i, each_char in enumerate(each_word):
left, right = each_word[:i], each_word[i+1:]
for char in 'abcdefghijklmnopqrstuvwxyz':
if each_word[i] == char:
continue
else:
new_word = left + char + right
if new_word in wordset:
words.append(new_word)
return words
算法說明
看似 string 其實是一個 Graph 的題目,透過 BFS 來分層遍歷,找到最淺能達到目標的點。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
get_next_word
這裡我們使用的方式比較單純,可以採取的策略有:
- 從 wordList 去反推下一層可能的文字
- 直接拆字去推,再去 wordList 找
個人使用的是第二種方法。
注意:加速技巧
原本題目使用的 wordList 搜尋時間為:O(n),
若改為 set, hashmap,時間可以壓縮至 O(1)
input handling
處理 input endWord 不在 wordList 的情況,輸出 0 。
Boundary conditions
迴圈結束於
- 找到目標
- 找不到目標,且沒有下一層 layer (全部都 visited)
Reference
⭐ Leetcode 解題紀錄 ⭐ | 題型 | 資料結構 | Python Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 |