Python•word-ladder/solution.py
from collections import deque
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
if endWord not in wordList:
return class="syntax-number">0
wordSet = set(wordList)
queue = deque([(beginWord, class="syntax-number">1)])
while queue:
current_word, steps = queue.popleft()
if current_word == endWord:
return steps
for i in range(len(current_word)):
for char in class="syntax-string">'abcdefghijklmnopqrstuvwxyz':
next_word = current_word[:i] + char + current_word[i+class="syntax-number">1:]
if next_word in wordSet:
queue.append((next_word, steps + class="syntax-number">1))
wordSet.remove(next_word)
return class="syntax-number">0
solution = Solution()
beginWord = class="syntax-string">"hit"
endWord = class="syntax-string">"cog"
wordList = [class="syntax-string">"hot", class="syntax-string">"dot", class="syntax-string">"dog", class="syntax-string">"lot", class="syntax-string">"log", class="syntax-string">"cog"]
print(solution.ladderLength(beginWord, endWord, wordList))