leetcode 127. Word Ladder 发表于 2018-12-19 | 分类于 leetcode 题目链接:leetcode 思路:回溯法 12345678910111213141516171819202122232425262728293031323334353637383940414243444546from collections import dequeclass Solution: def getNeighbors(self,word): neighbors = [] letters = 'abcdefghijklmnopqrstuvwxyz' for i in range(len(word)): for letter in letters: newWord = word[:i]+letter+word[i+1:] if newWord not in self.visitedSet and newWord in self.wordSet: if newWord == self.endWord: return [newWord] self.visitedSet.add(newWord) neighbors.append(newWord) return neighbors def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ if endWord not in wordList:return 0 level = 1 self.endWord = endWord self.visitedSet = set() self.wordSet = set(wordList) q = deque() q.append(beginWord) q.append('Level') while len(q) != 0: word = q.popleft() if word == 'Level': level += 1 if len(q) > 0: q.append('Level') continue neighbors = self.getNeighbors(word) if neighbors: print("level={},word={},neighbors={}".format(level,word,neighbors)) for neighbor in neighbors: if neighbor == self.endWord: return level+1 q.append(neighbor) return 0