LeetCode 127. [Python] Word Ladder
原题链接
中等
作者:
徐辰潇
,
2020-04-05 09:47:22
,
所有人可见
,
阅读 920
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
res = 0
Q = collections.deque()
Q.append(beginWord)
Set = set(wordList)
if endWord not in Set:
return 0
while(Q):
res += 1
n = len(Q)
for i in range(n):
word = Q.popleft()
for j in range(len(word)):
for ch in 'abcdefghijklmnopqrstuvwxyz':
word_copy = word[:j] + ch + word[j+1:]
if str(word_copy) == endWord:
return res + 1
if str(word_copy) in Set:
Q.append(str(word_copy))
Set.remove(str(word_copy))
return 0