-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord-Ladder
More file actions
46 lines (30 loc) · 1.25 KB
/
Word-Ladder
File metadata and controls
46 lines (30 loc) · 1.25 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
44
45
46
def ladderLength(beginWord, endWord, wordList):
word_set = set(wordList)
if endWord not in word_set:
return 0
begin_set = {beginWord}
end_set = {endWord}
visited = set()
level = 1
while begin_set and end_set:
# Always expand smaller set (optimization)
if len(begin_set) > len(end_set):
begin_set, end_set = end_set, begin_set
next_set = set()
for word in begin_set:
for i in range(len(word)):
for ch in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + ch + word[i+1:]
if new_word in end_set:
return level + 1
if new_word in word_set and new_word not in visited:
visited.add(new_word)
next_set.add(new_word)
begin_set = next_set
level += 1
return 0
# User Input
beginWord = input("Enter begin word: ")
endWord = input("Enter end word: ")
wordList = input("Enter word list (space separated): ").split()
print("Shortest transformation length:", ladderLength(beginWord, endWord, wordList))