Skip to content

Commit 767a8f1

Browse files
author
weiy
committed
word ladder medium
1 parent b7b4eb2 commit 767a8f1

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

BFS/WordLadder.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""
2+
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:
3+
4+
Only one letter can be changed at a time.
5+
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
6+
Note:
7+
8+
Return 0 if there is no such transformation sequence.
9+
All words have the same length.
10+
All words contain only lowercase alphabetic characters.
11+
You may assume no duplicates in the word list.
12+
You may assume beginWord and endWord are non-empty and are not the same.
13+
Example 1:
14+
15+
Input:
16+
beginWord = "hit",
17+
endWord = "cog",
18+
wordList = ["hot","dot","dog","lot","log","cog"]
19+
20+
Output: 5
21+
22+
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
23+
return its length 5.
24+
Example 2:
25+
26+
Input:
27+
beginWord = "hit"
28+
endWord = "cog"
29+
wordList = ["hot","dot","dog","lot","log"]
30+
31+
Output: 0
32+
33+
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
34+
35+
36+
这个BFS有点...
37+
38+
一开始的思路就是 BFS,写法不同。
39+
40+
一开始的写法是每次都从 wordList 里找单词,结果是有一个case跑不通。
41+
42+
后来实在没思路学习 Discuss 里的内容,Discuss 里的 BFS 是每一个都生成26个新的单词,然后判断是否在 wordList 中。
43+
44+
这种方法可以全部跑通...
45+
46+
可优化的点在于如何高效的找到存在于 _wordList 中可变换的值。
47+
48+
beat 66%
49+
50+
测试地址:
51+
https://leetcode.com/problems/word-ladder/description/
52+
53+
"""
54+
from collections import deque
55+
class Solution(object):
56+
def ladderLength(self, beginWord, endWord, wordList):
57+
"""
58+
:type beginWord: str
59+
:type endWord: str
60+
:type wordList: List[str]
61+
:rtype: int
62+
"""
63+
64+
if len(beginWord) == 1:
65+
return 2
66+
67+
_wordList = set(wordList)
68+
69+
result = deque([[beginWord, 1]])
70+
71+
while result:
72+
word, length = result.popleft()
73+
74+
if word == endWord:
75+
return length
76+
77+
_length = length + 1
78+
79+
for i in range(len(word)):
80+
for c in 'qwertyuiopasdfghjklzxcvbnm':
81+
new = word[:i]+c+word[i+1:]
82+
83+
if new in _wordList:
84+
_wordList.remove(new)
85+
result.append([new, _length])
86+
87+
return 0

0 commit comments

Comments
 (0)