forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword-ladder-ii.py
46 lines (37 loc) · 1.44 KB
/
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
37
38
39
40
41
42
43
44
45
# Time: O(n * d), n is length of string, d is size of dictionary
# Space: O(d)
from collections import defaultdict
from string import ascii_lowercase
class Solution(object):
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
dictionary = set(wordList)
result, cur, visited, found, trace = [], [beginWord], set([beginWord]), False, defaultdict(list)
while cur and not found:
for word in cur:
visited.add(word)
next = set()
for word in cur:
for i in xrange(len(word)):
for c in ascii_lowercase:
candidate = word[:i] + c + word[i + 1:]
if candidate not in visited and candidate in dictionary:
if candidate == endWord:
found = True
next.add(candidate)
trace[candidate].append(word)
cur = next
if found:
self.backtrack(result, trace, [], endWord)
return result
def backtrack(self, result, trace, path, word):
if not trace[word]:
result.append([word] + path)
else:
for prev in trace[word]:
self.backtrack(result, trace, [word] + path, prev)