-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0127-word-ladder.py
More file actions
36 lines (32 loc) · 1.18 KB
/
0127-word-ladder.py
File metadata and controls
36 lines (32 loc) · 1.18 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
# time complexity: O(n*m)
# space complexity: O(n*m)
from collections import deque
from typing import List
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordSet = set(wordList)
queue = deque()
queue.append(beginWord)
count = 1
while queue:
size = len(queue)
for _ in range(size):
currWord = queue.popleft()
if currWord == endWord:
return count
for wordIdx in range(len(currWord)):
for nextC in 'abcdefghijklmnopqrstuvwxyz':
nextWord = currWord[:wordIdx] + nextC + currWord[wordIdx + 1:]
if nextWord in wordSet:
queue.append(nextWord)
wordSet.remove(nextWord)
count += 1
return 0
beginWord = "hit"
endWord = "cog"
wordList = ["hot", "dot", "dog", "lot", "log", "cog"]
print(Solution().ladderLength(beginWord, endWord, wordList))
beginWord = "hit"
endWord = "cog"
wordList = ["hot", "dot", "dog", "lot", "log"]
print(Solution().ladderLength(beginWord, endWord, wordList))