127 wordLadder 使用BFS 和双向BFS

  1. Word Ladder
    Medium

3931

1319

Add to List

Share
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence 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:

Return 0 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: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

from collections import deque
import string

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        wordLength = len(beginWord)
        de = deque([beginWord])
        wordSet = set(wordList)
        if not endWord in wordSet: return 0
        depth = 0
        while len(de) > 0:
            depth += 1
            count = len(de)
            while count > 0:
                count -= 1
                word = de.pop()
                for i in range(wordLength):
                    for w in string.ascii_lowercase:
                        temp = word[:i]+w+word[i+1:]
                        if temp == endWord : return depth+1
                        if not temp in wordSet: continue
                        de.appendleft(temp)
                        wordSet.remove(temp)
                        
        return 0 

使用双向BFS

import string

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
            wordLength = len(beginWord)
            wordSet = set(wordList)
            if not endWord in wordSet: return 0
            s1 = {beginWord}
            s2 = {endWord}
            wordSet.remove(endWord)
            depth = 0
            
            while len(s1) > 0 and len(s2) > 0:
                # 交换两个set,始终使用最短的set来做BFS。
                if len(s1)> len(s2): s1,s2 = s2,s1
                depth = depth +1
                s = set()
                for w in s1:
                    for i in range(wordLength):
                        for char in string.ascii_lowercase:
                            temp = w[:i]+char+w[i+1:]
                            if temp in s2: return depth + 1
                            if not temp in wordSet: continue
                            s.add(temp)
                            wordSet.remove(temp)
                s1 = s
            
            return 0

使用for 循环生成list:

new_words = [
                    w[:i] + t + w[i+1:]  for t in string.ascii_lowercase for i in range(l)]

你可能感兴趣的:(127 wordLadder 使用BFS 和双向BFS)