给定一个起始字符串和一个目标字符串,现在将起始字符串按照特定的变换规则转换为目标字符串,求所有转换次数最少的转换过程。转换规则为每次只能改变字符串中的一个字符,且每次转换后的字符串都要在给定的字符串集合中。
注意点:
例子:
输入: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
输出:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
整体思想与Word Ladder一样,都是采用DFS的方法。不过要做出以下的变化:
注:图中的有些单词没有意义,只是单纯为了举例子,图对应的起始字符串为hit,给定的字符串集合为{“hot”,”hat”,”bit”,”him”,”bot”,”bim”}
class Solution(object):
def findLadders(self, beginWord, endWord, wordlist):
"""
:type beginWord: str
:type endWord: str
:type wordlist: Set[str]
:rtype: List[List[int]]
"""
def bfs(front_level, end_level, is_forward, word_set, path_dic):
if len(front_level) == 0:
return False
if len(front_level) > len(end_level):
return bfs(end_level, front_level, not is_forward, word_set, path_dic)
for word in (front_level | end_level):
word_set.discard(word)
next_level = set()
done = False
while front_level:
word = front_level.pop()
for c in ‘abcdefghijklmnopqrstuvwxyz‘:
for i in range(len(word)):
new_word = word[:i] + c + word[i + 1:]
if new_word in end_level:
done = True
add_path(word, new_word, is_forward, path_dic)
else:
if new_word in word_set:
next_level.add(new_word)
add_path(word, new_word, is_forward, path_dic)
return done or bfs(next_level, end_level, is_forward, word_set, path_dic)
def add_path(word, new_word, is_forward, path_dic):
if is_forward:
path_dic[word] = path_dic.get(word, []) + [new_word]
else:
path_dic[new_word] = path_dic.get(new_word, []) + [word]
def construct_path(word, end_word, path_dic, path, paths):
if word == end_word:
paths.append(path)
return
if word in path_dic:
for item in path_dic[word]:
construct_path(item, end_word, path_dic, path + [item], paths)
front_level, end_level = {beginWord}, {endWord}
path_dic = {}
bfs(front_level, end_level, True, wordlist, path_dic)
path, paths = [beginWord], []
construct_path(beginWord, endWord, path_dic, path, paths)
return paths
if __name__ == "__main__":
assert Solution().findLadders("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) == [
["hit", "hot", "dot", "dog", "cog"],
["hit", "hot", "lot", "log", "cog"]
]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
原文:http://blog.csdn.net/u013291394/article/details/51464671