题目:
题解:
class Solution:def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:ans = []if endWord not in wordList:return anssize = len(beginWord)cur_word_set = {beginWord}ws = set(wordList)# 用于控制bfs结束flag = Falseif beginWord in ws:ws.remove(beginWord)tmp = list('abcdefghijklmnopqrstuvwxyz')# key为当前单词,value为能到达该单词(bfs搜索)的单词列表,即该单词的parentword_dict = {}# bfswhile cur_word_set:# 该次bfs匹配到的单词match_set = set()for cur in cur_word_set:for i in range(size):for j in tmp:if cur[i] == j:continueword = cur[:i] + j + cur[i + 1:]# word在单词列表中if word in ws:# 匹配加入该单词match_set.add(word)# 为该单词维护parentif word not in word_dict:word_dict[word] = []word_dict[word].append(cur)# 到达终点 bfs结束if word == endWord:flag = True# 该次bfs结束,剔除掉匹配到的单词for el in match_set:ws.remove(el)# 下次bfs的parentcur_word_set = match_setif flag: break# 完成bfs开始dfs,通过endword反向找parent,直到找到beginword# 没有匹到endword,直接结束if not flag: return ansresult = [endWord]def dfs(cur_word):if cur_word == beginWord:ans.append(result[::-1])returnfor el in word_dict[cur_word]:result.append(el)dfs(el)result.pop()dfs(endWord)return ans