127. Word Ladder (Hard) - TengnanYao/daily_leetcode GitHub Wiki
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordList = set(wordList)
if endWord not in wordList:
return 0
seen = {beginWord}
q = [beginWord]
step = 1
while q:
step += 1
temp = []
for x in q:
for i in range(len(x)):
for c in "qwertyuiopasdfghjklzxcvbnm":
word = x[ : i] + c + x[i + 1 : ]
if word not in seen and word in wordList:
if word == endWord:
return step
temp.append(word)
seen.add(word)
q = temp
return 0