-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadder.py
More file actions
43 lines (32 loc) · 1.24 KB
/
WordLadder.py
File metadata and controls
43 lines (32 loc) · 1.24 KB
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
# Question link - https://leetcode.com/problems/word-ladder/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
# Base case
if endWord not in wordList:
return 0
# create the adjacency list
nei = collections.defaultdict(list)
wordList.append(beginWord)
# Createing the pattern
for word in wordList:
for i in range(len(word)):
pattern = word[:j] + "*" + word[j+1:]
nei[pattern].append(word)
# BFS
q = deque([beginWord])
visited = set([beginWord])
res = 1
while q:
for i in range(len(q)):
word = q.popleft()
if word == endWord:
return res
# neighbors patterns
for j in range(len(word)):
pattern = word[:j] + "*" + word[j+1:]
for neiWord in nei[pattern]:
if neiWord not in visited:
visited.add(neiWord)
q.append(neiWord)
res += 1
return 0