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
廣告