-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127. Word Ladder.py
38 lines (24 loc) · 1.03 KB
/
127. Word Ladder.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
import collections
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordList.append(beginWord)
graph = collections.defaultdict(list)
for word in wordList:
for i in range(len(beginWord)):
pattern = word[:i] + "*" + word[i+1:]
graph[pattern].append(word)
q = collections.deque()
visited = set([beginWord])
q.append((beginWord,1))
while q:
cur,step = q.popleft()
if cur == endWord:
return step
step += 1
for i in range(len(cur)):
pattern = cur[:i] + "*" + cur[i+1:]
for nextWord in graph[pattern]:
if nextWord not in visited:
visited.add(nextWord)
q.append((nextWord,step))
return 0