-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWord Ladder
53 lines (34 loc) · 1.35 KB
/
Word Ladder
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
50
51
52
53
// Word Ladder
# shortest transformation sequence length
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
available = set()
isPresent = False
for s in wordList:
available.add(s)
if s == endWord:
isPresent = True
if not isPresent:
return 0
Q = deque()
Q.append(beginWord)
level = 1
while len(Q) > 0:
n = len(Q)
for i in range(n):
s = Q.popleft()
A = list(s)
for j in range(len(A)):
for c in ascii_lowercase:
B = A[:]
B[j] = c
new_s = ''.join(B)
if new_s == s:
continue
if new_s == endWord:
return level + 1
if new_s in available:
Q.append(new_s)
available.remove(new_s)
level += 1
return 0