题目
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) 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”]
Return
[
[“hit”,”hot”,”dot”,”dog”,”cog”],
[“hit”,”hot”,”lot”,”log”,”cog”]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
题目要求
根Word Ladder 不同,此题要求找出所有将word1转化为word2的最短路径,每次转化只能改变一个字符,且转化后的单词要出现在单词表中。
解题思路
此题参考南郭子綦的思路。
依然是bfs的方法,但是与Word Ladder 不同的是,这是是在生成下一层转化之前把上一层出现过的单词从单词表中移除。而且为了去重,每层都是用set集合来存储每层的单词。为了记录这其中的路径,用一个字典来存储每个单词的所有前驱。最后再生成从前驱中生成所有的路径。
代码
class Solution(object):
def findLadders(self, beginWord, endWord, wordlist):
"""
:type beginWord: str
:type endWord: str
:type wordlist: Set[str]
:rtype: List[List[int]]
"""
def buildPath(path,word):
if len(preMap[word]) == 0:
result.append([word] + path)
return
path.insert(0,word)
for w in preMap[word]:
buildPath(path,w)
path.pop(0)
length = len(beginWord)
preMap = {}
for word in wordlist:
preMap[word] = []
result = []
cur_level = set()
cur_level.add(beginWord)
while True:
pre_level = cur_level
cur_level = set()
for word in pre_level: wordlist.remove(word)
for word in pre_level:
for i in range(length):
left = word[:i]
right = word[i+1:]
for c in 'abcdefghijklmnopqrstuvwxyz':
if c != word[i]:
nextWord = left + c + right
if nextWord in wordlist:
preMap[nextWord].append(word)
cur_level.add(nextWord)
if len(cur_level) == 0:
return []
if endWord in cur_level:
break
buildPath([],endWord)
return result