Python程序:查找将一个单词更改为另一个单词所需的步数
假设我们有一个名为dictionary的单词列表,以及另外两个字符串start和end。我们希望通过一次更改一个字符来从start到达end,并且每个生成的单词也应该在dictionary中。单词区分大小写。因此,我们必须找到到达end所需的最小步数。如果不可能,则返回-1。
因此,如果输入类似于dictionary = ["may", "ray", "rat"] start = "rat" end = "may",则输出为3,因为我们可以选择此路径:["rat", "ray", "may"]。
为了解决这个问题,我们将遵循以下步骤:
dictionary := a new set with all unique elements present in q = a double ended queue with a pair (start, 1) while q is not empty, do (word, distance) := left element of q, and delete the left element if word is same as end, then return distance for i in range 0 to size of word - 1, do for each character c in "abcdefghijklmnopqrstuvwxyz", do next_word := word[from index 0 to i - 1] concatenate c concatenate word[from index (i + 1) to end] if next_word is in dictionary, then delete next_word from dictionary insert (next_word, distance + 1) at the end of q return -1
示例(Python)
让我们看看下面的实现,以便更好地理解:
from collections import deque class Solution: def solve(self, dictionary, start, end): dictionary = set(dictionary) q = deque([(start, 1)]) while q: word, distance = q.popleft() if word == end: return distance for i in range(len(word)): for c in "abcdefghijklmnopqrstuvwxyz": next_word = word[:i] + c + word[i + 1 :] if next_word in dictionary: dictionary.remove(next_word) q.append((next_word, distance + 1)) return -1 ob = Solution() dictionary = ["may", "ray", "rat"] start = "rat" end = "may" print(ob.solve(dictionary, start, end))
输入
["may", "ray", "rat"], "rat", "may"
输出
3
广告