Skip to content

Commit 4b69f87

Browse files
authored
Create 127-Word-Ladder.py
1 parent 089c7ae commit 4b69f87

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

127-Word-Ladder.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
3+
if endWord not in wordList:
4+
return 0
5+
6+
nei = collections.defaultdict(list)
7+
wordList.append(beginWord)
8+
for word in wordList:
9+
for j in range(len(word)):
10+
pattern = word[:j] + "*" + word[j + 1:]
11+
nei[pattern].append(word)
12+
13+
visit = set([beginWord])
14+
q = deque([beginWord])
15+
res = 1
16+
while q:
17+
for i in range(len(q)):
18+
word = q.popleft()
19+
if word == endWord:
20+
return res
21+
for j in range(len(word)):
22+
pattern = word[:j] + "*" + word[j + 1:]
23+
for neiWord in nei[pattern]:
24+
if neiWord not in visit:
25+
visit.add(neiWord)
26+
q.append(neiWord)
27+
res += 1
28+
return 0

0 commit comments

Comments
 (0)