【发布时间】:2018-06-22 09:22:30
【问题描述】:
我正在尝试解决 leetcode 问题(https://leetcode.com/problems/word-ladder/description/):
给定两个单词(beginWord 和 endWord)和一个字典的单词列表,求从 beginWord 到 endWord 的最短转换序列的长度,这样:
一次只能更改一个字母。 每个转换后的单词都必须存在于单词列表中。请注意,beginWord 不是转换后的单词。 注意:
如果没有这样的转换序列,则返回 0。 所有单词的长度相同。 所有单词仅包含小写字母字符。 您可以假设单词列表中没有重复项。 你可以假设 beginWord 和 endWord 是非空的并且不相同。
输入:
beginWord = "命中", endWord = "齿轮", wordList = ["hot","dot","dog","lot","log","cog"]
输出:
5
解释:
因为一个最短的变换是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",返回它的长度 5。
import queue
class Solution:
def isadjacent(self,a, b):
count = 0
n = len(a)
for i in range(n):
if a[i] != b[i]:
count += 1
if count > 1:
return False
if count == 1:
return True
def ladderLength(self,beginWord, endWord, wordList):
word_queue = queue.Queue(maxsize=0)
word_queue.put((beginWord,1))
while word_queue.qsize() > 0:
queue_last = word_queue.get()
index = 0
while index != len(wordList):
if self.isadjacent(queue_last[0],wordList[index]):
new_len = queue_last[1]+1
if wordList[index] == endWord:
return new_len
word_queue.put((wordList[index],new_len))
wordList.pop(index)
index-=1
index+=1
return 0
有人可以建议如何优化它并防止错误!
【问题讨论】:
-
我会从开头词和结尾词进行搜索,并测试它们是否在某个级别“在中间相遇”。
-
作为参考,这相当于计算Edit Distance,其中存在动态规划解决方案。还请用简单的英语发布您尝试实现的算法。我们可以将此与您发布的代码进行比较并提供更好的帮助。
-
不要重新访问你已经访问过的单词
-
@juvian OP 没有:访问过的单词从
wordList中删除 -
@yeputons 如果 wordList 是一个列表,按索引弹出太贵了
标签: python algorithm data-structures queue breadth-first-search