-
Notifications
You must be signed in to change notification settings - Fork 0
/
126-Word_Ladder_II.py
36 lines (31 loc) · 1.28 KB
/
126-Word_Ladder_II.py
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
34
35
36
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
tree, words, len_w = collections.defaultdict(set), set( wordList ), len(beginWord)
if endWord not in words:
return []
found, q, nextq = False, {beginWord}, set()
while q and not found:
words -= set(q)
for x in q:
# a -> z
for char in string.ascii_lowercase:
for i in range(len_w):
test = x[:i] + char + x[i+1:]
if test == endWord:
found = True
tree[x].add(test)
elif test in words:
nextq.add(test)
tree[x].add(test)
q, nextq = nextq, set()
def back(x):
if x == endWord:
return [[x]]
else:
ans = []
for test in tree[x]:
for y in back(test):
ans.append( [x] + y )
return ans
# [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)]
return back(beginWord)