[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:

  1. Only one letter can be changed at a time
  2. 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)

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10924963.html

时间: 2024-10-29 19:09:48

[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS的相关文章

leetcode 126. Word Ladder II

1 import string 2 import collections 3 4 class Solution(object): 5 def findLadders(self, begin, end, words_list): 6 '''删除起至单词''' 7 words_list.discard(begin) 8 words_list.discard(end) 9 10 '''根据tree递归构造路径''' 11 def construct_paths(source, dest, tree):

Java for LeetCode 126 Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time    Each intermediate word must exist in the dictionary For example, Given:start = "

LeetCode OJ - Word Ladder 2

我发现在leetcode上做题,当我出现TLE问题时,往往是代码有漏洞,有些条件没有考虑到,这道题又验证了我这一想法. 这道题是在上一道的基础上进一步把所有可能得转换序列给出. 同样的先是BFS,与此同时需要一个hashMap记录下每个节点,和他所有父节点的对应关系,然后通过DFS,回溯所有可能的路径. 下面是AC代码. 1 /** 2 * Given two words (start and end), and a dictionary, find all shortest transform

LeetCode OJ - Word Ladder

我觉得这道题比较难,主要是因为对于我来说: 1. 我没有把这个问题联想到树的宽度遍历(即便没有考虑树的宽度遍历,也是可以做的,但是我一开始实现的代码却是深度遍历,后来发现树的BFS一般使用queue实现的,貌似没有递归的方法??) 2. 即使在意识到用BFS,却还有一个陷阱:我是对字典进行了BFS,这个说实话,代码长,还TLE: 后来参考了前辈的代码,采用对26个单词进行枚举,才解决了这个问题. 下面是AC代码: 1 /** 2 * Given two words (start and end)

126. Word Ladder II(js)

126. 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

【LeetCode】Word Ladder 字符串

题目:Word Ladder <span style="font-size:18px;">/**LeetCode word ladder * 题目:给定一个起始单词和一个终结单词以及一个字典,要求每次变换一个字符,成为字典中新的词,直到变为最后的词,要求其最短路径 * 思路:利用队列,先弹出第一个词,分别将词中每一个字符替换直到找到一个字典中存在的词,加入队列,直到匹配的词是最后一个,此时终止 * 如果没有这样的路径,则返回0 */ package javaTrain; i

[LeetCode][JavaScript]Word Ladder

https://leetcode.com/problems/word-ladder/ Word Ladder Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time Each

[Leetcode][JAVA] Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example, Given:start = "hit

【leetcode】126. Word Ladder II

题目如下: 解题思路:DFS或者BFS都行.本题的关键在于减少重复计算.我采用了两种方法:一是用字典dic_ladderlist记录每一个单词可以ladder的单词列表:另外是用dp数组记录从startword开始到wordlist每一个word的最小转换次数,这一点非常重要,可以过滤很多无效的运算. 代码如下: class Solution(object): def getLadderList(self, w,d): l = [] r = [] for i in xrange(26): l.a