今天和大家聊的问题叫做 单词接龙 II,我们先来看题面:https://leetcode-cn.com/problems/word-ladder-ii/
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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
题意
给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:
每次转换只能改变一个字母。
转换后得到的单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回一个空列表。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
样例
示例 1: 输入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 输出: [ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ] 示例 2: 输入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] 输出: [] 解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。
解题
先利用BFS从endWord到beginWord得到满足连通要求的单词到endWord的最短距离dist。
再利用DFS遍历从beginWord到endWord的得到满足dist的所有单词序列。(注:这里DFS利用递归来做,不能用栈,因为要得到所有满足要求的单词序列)
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: wordList=set(wordList) wordList.add(beginWord) #wordList.append(beginWord) dist=self.bfs(endWord,wordList) res=[] self.dfs(beginWord,endWord,wordList,dist,[beginWord],res) return res #bfs记录点到终点的最短距离:end -> start def bfs(self,begin,wordList): dist={} dist[begin]=0 queue=[begin] while queue: L=len(queue) for _ in range(L): word=queue.pop(0) for w in self.nextWord(word,wordList): if w not in dist: dist[w]=dist[word]+1 queue.append(w) return dist #利用递归来记录路径:从start -> end def dfs(self,curr,end,wordList,dist,path,res): if curr==end: res.append(list(path)) for w in self.nextWord(curr,wordList): if dist[w]==dist[curr]-1: path.append(w) self.dfs(w,end,wordList,dist,path,res) path.pop() def nextWord(self,word,wordList): res=[] for i in range(len(word)): for letter in "abcdefghijklmnopqrstuvwxyz": next_=word[0:i]+letter+word[i+1::] if next_!=word and next_ in wordList: res.append(next_) return res
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。