-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem126.py
More file actions
57 lines (52 loc) · 1.93 KB
/
problem126.py
File metadata and controls
57 lines (52 loc) · 1.93 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution(object):
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
if not endWord in wordList:
return []
if not wordList:
return []
from collections import defaultdict
neightbors = defaultdict(list)
wordLength = len(wordList[0])
for word in wordList:
for index in range(wordLength):
formats = word[:index] + '_' + word[index+1:]
neightbors[formats].append(word)
self.visited = set([])
stack = [[beginWord],[endWord]]
ans = []
while stack:
nextStack = []
while stack:
beforePath = stack.pop()
previousWord = beforePath[-1]
for index in range(wordLength):
formats = previousWord[:index] + '_' + previousWord[index+1:]
for nextWord in neightbors[formats]:
if nextWord in beforePath:
continue
if nextWord == endWord:
tmpRst = beforePath + [nextWord]
if tmpRst not in ans:
ans.append(tmpRst)
elif nextWord == beginWord:
tmpRst = (beforePath + [nextWord])[::-1]
if tmpRst not in ans:
ans.append(tmpRst)
else:
nextStack.append(beforePath + [nextWord])
if ans == []:
stack = nextStack
else:
break
return ans
s = Solution()
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
print s.findLadders(beginWord, endWord, wordList)