-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0127.py
More file actions
26 lines (21 loc) · 877 Bytes
/
0127.py
File metadata and controls
26 lines (21 loc) · 877 Bytes
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
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
graph = defaultdict(list)
for word in wordList:
for index in range(len(beginWord)):
graph[word[:index] + "_" + word[index+1:]].append(word)
used = set()
queue = deque()
queue.append((beginWord, 1))
while queue:
word, depth = queue.popleft()
if word == endWord:
return depth
for index in range(len(word)):
node = word[:index] + "_" + word[index+1:]
for pot in graph[node]:
if pot not in used:
queue.append((pot, depth + 1))
used.add(pot)
graph[node] = []
return 0