-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127_wordLadder.py
49 lines (32 loc) · 1.28 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
44
45
46
47
48
49
# 127. Word Ladder
from collections import defaultdict, deque
# Neetcode's explanation: https://www.youtube.com/watch?v=h9iTnkgv05E
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
#Create adjacency graph
nei = defaultdict(list)
wordList.append(beginWord)
for word in wordList:
for j in range(len(word)):
pattern = word[:j]+"*"+word[j+1:]
nei[pattern].append(word)
#BFS
visit = set([beginWord])
q = deque([beginWord])
res = 1
while q:
for i in range(len(q)):
word = q.popleft()
if word == endWord:
return res
# Get neighbors of word
for j in range(len(word)):
pattern = word[:j]+"*"+word[j+1:]
for neiWord in nei[pattern]:
if neiWord not in visit:
visit.add(neiWord)
q.append(neiWord)
res+=1
return 0