题目
给定两个单词(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" 不在字典中,所以无法进行转换。
【中等】
【分析】BFS
想法是这个想法,但是超时了。。。
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
queue=[beginWord]
seen={beginWord:1}
while queue:
word=queue.pop(0)
for i in range(len(word)):
index=list(range(i))+list(range(i+1,len(word)))
w0=[word[_] for _ in index]
for w in wordList:
if w!=word:
w1=[w[_] for _ in index]
if w1==w0 and w not in seen:
if w==endWord:
return(seen[word]+1)
queue.append(w)
seen[w]=seen[word]+1
return 0
需要改进,改进方向可以是单词预处理部分,怎么来处理单词只改变其中一个字母变成wordList中的某单词。
【分析2】单词预处理,举个栗子:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
对 h o t hot hot处理,有三种方式: ∗ o t , h ∗ t , h o ∗ *ot,h*t,ho* ∗ot,h∗t,ho∗,同理,其他单词都有三种处理方式,让 ∗ o t , h ∗ t , h o ∗ *ot,h*t,ho* ∗ot,h∗t,ho∗等为key,然后让处理成这种方式的单词作为value。
这一过程就像是在处理无向无权图,最后化为求最短路径问题。
from collections import defaultdict
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList or not beginWord or not endWord or not wordList:
return 0
#预处理
dic=defaultdict(list)
L=len(wordList[0])
for word in wordList:
for i in range(L):
dic[word[0:i]+"*"+word[i+1::]].append(word)
queue=[beginWord]
seen={beginWord:1}
while queue:
word=queue.pop(0)
for i in range(L):
next_word=dic[word[0:i]+"*"+word[i+1::]]
for w in next_word:
if w==endWord:
return(seen[word]+1)
if w not in seen:
queue.append(w)
seen[w]=seen[word]+1
return 0
时间复杂度:
O
(
M
×
N
)
O
(
M
×
N
)
O(M \times N)O(M×N)
O(M×N)O(M×N),其中 M 是单词的长度 N 是单词表中单词的总数。找到所有的变换需要对每个单词做 M 次操作。同时,最坏情况下广度优先搜索也要访问所有的 N个单词。
空间复杂度:
O
(
M
×
N
)
O
(
M
×
N
)
O(M \times N)O(M×N)
O(M×N)O(M×N),要在 dic 字典中记录每个单词的 M 个通用状态。访问数组的大小是 N。广搜队列最坏情况下需要存储 N 个单词。
【注】当字典中的value是一个列表时,可以利用collections中的defaultdict模块做到,之前用dict直接做没有这个方便。
【分析3】双向广度优先搜索,即从beginWord和endWord两边同时开始搜索,搜索结束的条件是找到一个单词被两边都搜索过。所以,需要记录两边分别走的搜索步数,还有两边分别访问过的单词。
下面给出官方参考,我懒得再写一遍了,下次自己再考虑写一写
from collections import defaultdict
class Solution(object):
def __init__(self):
self.length = 0
# Dictionary to hold combination of words that can be formed,
# from any given word. By changing one letter at a time.
self.all_combo_dict = defaultdict(list)
def visitWordNode(self, queue, visited, others_visited):
current_word, level = queue.pop(0)
for i in range(self.length):
# Intermediate words for current word
intermediate_word = current_word[:i] + "*" + current_word[i+1:]
# Next states are all the words which share the same intermediate state.
for word in self.all_combo_dict[intermediate_word]:
# If the intermediate state/word has already been visited from the
# other parallel traversal this means we have found the answer.
if word in o thers_visited:
return level + others_visited[word]
if word not in visited:
# Save the level as the value of the dictionary, to save number of hops.
visited[word] = level + 1
queue.append((word, level + 1))
return None
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList or not endWord or not beginWord or not wordList:
return 0
# Since all words are of same length.
self.length = len(beginWord)
for word in wordList:
for i in range(self.length):
# Key is the generic word
# Value is a list of words which have the same intermediate generic word.
self.all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)
# Queues for birdirectional BFS
queue_begin = [(beginWord, 1)] # BFS starting from beginWord
queue_end = [(endWord, 1)] # BFS starting from endWord
# Visited to make sure we don't repeat processing same word
visited_begin = {beginWord: 1}
visited_end = {endWord: 1}
ans = None
# We do a birdirectional search starting one pointer from begin
# word and one pointer from end word. Hopping one by one.
while queue_begin and queue_end:
# One hop from begin word
ans = self.visitWordNode(queue_begin, visited_begin, visited_end)
if ans:
return ans
# One hop from end word
ans = self.visitWordNode(queue_end, visited_end, visited_begin)
if ans:
return ans
return 0