leetcode @python 127. Word Ladder
题目链接
https://leetcode.com/problems/word-ladder/
题目原文
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
题目大意
给出开始单词、结束单词以及一个词典,求出从开始单词变换到结束单词所需要经过的词数,每次变换只能改变一个字母(若找不到这样的变化,返回0)
解题思路
根据开始单词,变换其中任意一个位置的字母,看新生成的单词是否在字典中出现,若新生成的单词等于结束单词,则结束,否则,继续变换新生成的单词
代码
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
length = 2
words = set([beginWord])
wordList.discard(beginWord)
wordList.discard(endWord)
while words:
newwords = set()
for word in words:
for i in range(len(word)):
for c in "abcdefghijklmnopqrstuvwxyz":
new_word = word[:i] + c + word[i + 1:]
if new_word == endWord:
return length
if new_word in wordList:
newwords.add(new_word)
words = newwords
length += 1
wordList -= words
return 0