forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
word_ladder.py
62 lines (58 loc) · 1.78 KB
/
word_ladder.py
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
54
55
56
57
58
59
60
61
62
"""
Given two words (beginWord and endWord), and a dictionary's word list,
find the length of shortest transformation sequence
from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
"""
def ladderLength(beginWord, endWord, wordList):
"""
Bidirectional BFS!!!
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
beginSet = set()
endSet = set()
beginSet.add(beginWord)
endSet.add(endWord)
result = 2
while len(beginSet) != 0 and len(endSet) != 0:
if len(beginSet) > len(endSet):
beginSet, endSet = endSet, beginSet
nextBeginSet = set()
for word in beginSet:
for ladderWord in wordRange(word):
if ladderWord in endSet:
return result
if ladderWord in wordList:
nextBeginSet.add(ladderWord)
wordList.remove(ladderWord)
beginSet = nextBeginSet
result += 1
print(beginSet)
print(result)
return 0
def wordRange(word):
for ind in range(len(word)):
tempC = word[ind]
for c in [chr(x) for x in range(ord('a'), ord('z')+1)]:
if c != tempC:
yield word[:ind] + c + word[ind+1:]
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
print(ladderLength(beginWord, endWord, wordList))