forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-ladder.py
31 lines (26 loc) · 986 Bytes
/
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
# Time: O(n * d), n is length of string, d is size of dictionary
# Space: O(d)
from string import ascii_lowercase
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
distance, cur, visited, lookup = 0, [beginWord], set([beginWord]), set(wordList)
while cur:
next_queue = []
for word in cur:
if word == endWord:
return distance + 1
for i in xrange(len(word)):
for j in ascii_lowercase:
candidate = word[:i] + j + word[i+1:]
if candidate not in visited and candidate in lookup:
next_queue.append(candidate)
visited.add(candidate)
distance += 1
cur = next_queue
return 0