forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathword-ladder.py
66 lines (61 loc) · 2.1 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
63
64
65
66
# Time: O(b^(d/2)), b is the branch factor of bfs, d is the result depth
# Space: O(w * l), w is the number of words, l is the max length of words
from string import ascii_lowercase
# two-end bfs
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
words = set(wordList)
if endWord not in words:
return 0
left, right = {beginWord}, {endWord}
ladder = 2
while left:
words -= left
new_left = set()
for word in left:
for new_word in (word[:i]+c+word[i+1:] for i in xrange(len(beginWord)) for c in ascii_lowercase):
if new_word not in words:
continue
if new_word in right:
return ladder
new_left.add(new_word)
left = new_left
ladder += 1
if len(left) > len(right):
left, right = right, left
return 0
# Time: O(b^d), b is the branch factor of bfs, d is the result depth
# Space: O(w * l), w is the number of words, l is the max length of words
class Solution2(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
lookup = set(wordList)
if endWord not in lookup:
return 0
ladder = 2
q = [beginWord]
while q:
new_q = []
for word in q:
for i in xrange(len(word)):
for j in ascii_lowercase:
new_word = word[:i] + j + word[i+1:]
if new_word == endWord:
return ladder
if new_word in lookup:
lookup.remove(new_word)
new_q.append(new_word)
q = new_q
ladder += 1
return 0