-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path127.py
More file actions
28 lines (28 loc) · 965 Bytes
/
Copy path127.py
File metadata and controls
28 lines (28 loc) · 965 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
27
28
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
n, count = len(beginWord), 0
dict = {}
for word in wordList:
dict[word] = 1
queue = [beginWord]
size = 1
word = beginWord
while len(queue) > 0:
word = queue[0]
if word == endWord:
break
queue = queue[1:]
for i in range(len(word)):
temp = word
for j in range(26):
if chr(ord('a') + j) == word[i]:
continue
temp = temp[:i] + chr(ord('a') + j) + temp[i + 1:]
if temp in dict:
queue.append(temp)
del dict[temp]
size -= 1
if size == 0:
size = len(queue)
count += 1
return count + 1 if word == endWord else 0