码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS

时间:2019-05-26 09:45:18      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:rdl   lis   ssi   lan   rac   code   cas   append   generate   

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)

 

[LeetCode] 126. Word Ladder II_Hard tag: BFS&DFS

标签:rdl   lis   ssi   lan   rac   code   cas   append   generate   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!