Word Ladder

xiaoxiao2021-02-28  77

这题主要是换个思路会简单很多。不用BFS而用DFS

class Solution(object): def ladderLength(self, beginWord, endWord, wordList): wordList.add(endWord) queue = collections.deque([[beginWord, 1]]) while queue: word, length = queue.popleft() if word == endWord: return length for i in range(len(word)): for c in 'abcdefghijklmnopqrstuvwxyz': next_word = word[:i] + c + word[i+1:] if next_word in wordList: wordList.remove(next_word) queue.append([next_word, length + 1]) return 0
转载请注明原文地址: https://www.6miu.com/read-72114.html

最新回复(0)