-
Notifications
You must be signed in to change notification settings - Fork 0
/
127.WordLadder.py
43 lines (42 loc) · 1.26 KB
/
127.WordLadder.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
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
def addjWords(word, visited):
res = []
count = 0
for item in wordList:
if item in visited:
continue
for i in range(len(word)):
if word[i] != item[i]:
count += 1
if count == 1:
res.append(item)
count = 0
return res
# create addj map
addjMap = {}
visited = set()
queue = []
queue.append(beginWord)
shortest = 0
while queue:
current = queue.pop(0)
if current == endWord:
return shortest - 1
tmp = addjWords(current, visited)
addjMap[current] = tmp
visited.add(current)
for i in tmp:
queue.append(i)
visited.add(i)
shortest += 1
return 0
s = Solution()
res = s.ladderLength(beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"])
print(res)