leetcode 127 單詞接龍 python

2021-10-23 13:06:43 字數 1558 閱讀 7800

給定兩個單詞(beginword 和 endword)和乙個字典,找到從 beginword 到 endword 的最短轉換序列的長度。轉換需遵循如下規則:

每次轉換只能改變乙個字母。

轉換過程中的中間單詞必須是字典中的單詞。

說明:

示例 1:

輸入:

beginword = "hit",

endword = "cog",

wordlist = ["hot","dot","dog","lot","log","cog"]

輸出: 5

解釋: 乙個最短轉換序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",

返回它的長度 5。

示例 2:

輸入:

beginword = "hit"

endword = "cog"

wordlist = ["hot","dot","dog","lot","log"]

輸出: 0

解釋: endword "cog" 不在字典中,所以無法進行轉換。

class

solution

(object):

defladderlength

(self, beginword, endword, wordlist)

:# 雙向bfs

if endword not

in wordlist:

return

0 front =

back =

dist =

1 wordlist =

set(wordlist)

word_len =

len(beginword)

while front:

dist +=

1 next_front =

set(

)for word in front:

for i in

range

(word_len)

:for c in string.lowercase:

if c != word[i]

: new_word = word[

:i]+ c + word[i+1:

]if new_word in back:

return dist

if new_word in wordlist:

next_front.add(new_word)

wordlist.remove(new_word)

front = next_front

iflen(back)

<

len(front)

: front, back = back, front

return

0

LeetCode 127 單詞接龍

解題思路 1 這道題要找乙個最短路徑,可以聯想到圖的相關演算法 雖然我當時沒想到 那麼是不是應該使用最短路徑的相關演算法呢。其實不用 因為這個圖里每條邊的長度都是1,用乙個廣度優先演算法就搞定了。2規模的問題,如果你遍歷list裡的每個單詞的話,你會發現一直超時,因為有的list的規模給到了上千,每...

Leetcode 127單詞接龍

給定兩個單詞 beginword 和 endword 和乙個字典,找到從 beginword 到 endword 的最短轉換序列的長度。轉換需遵循如下規則 每次轉換只能改變乙個字母。轉換過程中的中間單詞必須是字典中的單詞。說明 示例 1 輸入 beginword hit endword cog wo...

Leetcode 127 單詞接龍

給定兩個單詞 beginword 和 endword 和乙個字典,找到從 beginword 到 endword 的最短轉換序列的長度。轉換需遵循如下規則 每次轉換只能改變乙個字母。轉換過程中的中間單詞必須是字典中的單詞。說明 如果不存在這樣的轉換序列,返回 0。所有單詞具有相同的長度。所有單詞只由...