-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode126.py
More file actions
33 lines (33 loc) · 1.52 KB
/
Copy pathLeetcode126.py
File metadata and controls
33 lines (33 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
wordList.append(beginWord)
### 构建具有邻接关系的桶
buckets = defaultdict(list)
for word in wordList:
for i in range(len(beginWord)):
match = word[:i] + '_' + word[i+1:]
buckets[match].append(word)
##### BFS遍历
preWords = defaultdict(list) # 前溯词列表
toSeen = deque([(beginWord, 1)]) # 待遍历词及深度
beFound = {beginWord:1} # 已探测词列表
while toSeen:
curWord, level = toSeen.popleft()
for i in range(len(beginWord)):
match = curWord[:i] + '_' + curWord[i+1:]
for word in buckets[match]:
if word not in beFound:
beFound[word] = level+1
toSeen.append((word, level+1))
if beFound[word] == level+1: # 当前深度等于该词首次遍历深度,则仍应加入前溯词列表
preWords[word].append(curWord)
if endWord in beFound and level+1 > beFound[endWord]: # 已搜索到目标词,且完成当前层遍历
break
#### 列表推导式输出结果
if endWord in beFound:
res = [[endWord]]
while res[0][0] != beginWord:
res = [[word] + r for r in res for word in preWords[r[0]]]
return res
else:
return []