127 單詞接龍

2021-09-09 08:54:04 字數 1604 閱讀 4951

思路和126差不多,區別在於只用bfs,每次訪問一層,用乙個map來儲存訪問過的結點以及與起點的距離,避免重複訪問。最後輸出map中的終點項即可

import queue

class solution:

def ladderlength(self, beginword, endword, wordlist):

""":type beginword: str

:type endword: str

:type wordlist: list[str]

:rtype: int

"""nodeneighbors = {} #所有鄰居資訊

dict = set(wordlist)

distances = {} #所有距離資訊

dict.add(beginword)

self.bfs(beginword, endword, dict, nodeneighbors, distances)

if endword in distances:

return distances[endword] + 1

else: #若不存在,說明無法到達

return 0

def bfs(self, start, end, dict, nodeneighbors, distances):

for d in dict:

nodeneighbors[d] =

q = queue.queue()

q.put(start)

distances[start] = 0

while not q.empty():

count = q.qsize()

foundend = false

for i in range(count):

cur = q.get()

neighbors = self.getneighbors(cur, dict)

for neighbor in neighbors:

if neighbor not in distances: #避免重複訪問

distances[neighbor] = distances[cur] + 1

if neighbor == end:

foundend = true

else:

q.put(neighbor)

if foundend:

break

def getneighbors(self, nodestring, dict):

res =

chs = list(nodestring)

for i in range(len(chs)):

for ch in 'abcdefghijklmnopqrstuvwxyz':

if ch == chs[i]: #跳過,換成其他字元

continue

tmp = chs[i]

chs[i] = ch #替換

newstring = "".join(chs)

if newstring in dict:

chs[i] = tmp #還原

return res

127 單詞接龍

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

127 單詞接龍

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

127 單詞接龍

leetcode 127.單詞接龍 最短問題 bfs 廣度優先遍歷 廣度優先遍歷 佇列 queue 先進先出 是 bfs 的核心 1.1 visset 儲存已經走過的節點路徑 將 list 換成 set 可以更高效率的找到是否存在重複元素 雙向廣度優先遍歷 去掉了 queue 佇列 使用了 兩個 s...