给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出: 5
解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5。
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: 0
解释: endWord "cog" 不在字典中,所以无法进行转换。
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
w_len = len(wordList[0])
pattern_dict = {}
used_dict = {}
for word in wordList:
used_dict[word] = False
for i in range(w_len):
tmp_list = list(word)
tmp_list[i] = '*'
pattern = ''.join(tmp_list)
if pattern not in pattern_dict:
pattern_dict[pattern] = []
pattern_dict[pattern].append(word)
#print(pattern_dict)
queue = [(beginWord,1)]
if beginWord in used_dict:
used_dict[beginWord] = True
while len(queue)>0:
#print(queue)
queue_size = len(queue)
for q_i in range(queue_size):
cur_word,step = queue.pop(0)
match_flag = False
for s_i in range(w_len):
tmp_list = list(cur_word)
tmp_list[s_i] = '*'
cur_pattern = ''.join(tmp_list)
if cur_pattern in pattern_dict:
for match_word in pattern_dict[cur_pattern]:
if match_word == endWord:
#print((cur_word,step),(match_word,step+1))
return step+1
if used_dict[match_word] is False:
match_flag = True
used_dict[match_word] = True
queue.append((match_word,step+1))
return 0