[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS
Posted johnsonxiong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS相关的知识,希望对你有一定的参考价值。
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.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Example 2:
Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
这个是在[LeetCode] 127. Word Ladder _Medium tag: BFS的基础上,要求求出所有的方案,所以需要加上dfs来获得所有的path。不过这个方案是time limited exceeded.
Code:
import collections class Solution: def wordLadder2(self, beginWord, endWord, wordList): n, ans, wordSet = len(beginWord), [], set(wordList) if endWord not in wordSet: return ans wordDict = self.bfs(beginWord, endWord, wordSet) self.dfs(ans, beginWord, endWord, [beginWord], wordDict) return ans def bfs(self, beginWord, endWord, wordSet): queue, wordDict = collections.deque([beginWord]), {beginWord: 1} while queue: word = queue.popleft() if word == endWord: return wordDict for newWord in self.generateNewWords(word): if newWord in wordSet and newWord not in wordDict: queue.append(newWord) wordDict[newWord] = wordDict[word] + 1 return wordDict def generateNewWords(self, word): n, newWords = len(word), [] for i in range(n): for c in ‘qwertyuiopasdfghjklzxcvbnm‘: if c != word[i]: newWords.append(word[:i] + c + word[i + 1:]) return newWords def dfs(self, ans, start, end, path, wordDict): if end in wordDict and len(path) <= wordDict[end]: if start == end: ans.append(path) for newWord in self.generateNewWords(start): if newWord in wordDict and wordDict[newWord] == wordDict[word] + 1: self.dfs(ans, newWord, end, path + [newWord], wordDict)
以上是关于[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 126. Word Ladder II 单词接龙 II(困难)