https://leetcode.com/problems/word-ladder/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordLength = len(wordList[0])
curWordSet = set(wordList)
dq = collections.deque()
answer = 0
if endWord not in curWordSet:
return 0
dq.append((beginWord, 1))
while dq:
word, depth = dq.popleft()
if word == endWord:
answer = depth
break
for i in range(wordLength):
for c in 'abcdefghijklmnopqrstuvwxyz':
newWord = word[:i] + c + word[i+1:]
if newWord in curWordSet:
curWordSet.discard(newWord)
dq.append((newWord, depth + 1))
return answer