Skip to content

Commit f3e2128

Browse files
committedNov 18, 2020
feat: word-ladder
1 parent 0434d75 commit f3e2128

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
 

‎bfs.word-ladder.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import List
2+
from collections import deque
3+
4+
class Solution:
5+
"""
6+
127. 单词接龙
7+
https://leetcode-cn.com/problems/word-ladder/description/
8+
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
9+
a - 每次转换只能改变一个字母。
10+
b - 转换过程中的中间单词必须是字典中的单词。
11+
https://leetcode-cn.com/problems/word-ladder/solution/python3-bfshe-shuang-xiang-bfsshi-xian-dan-ci-jie-/
12+
"""
13+
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
14+
st = set(wordList)
15+
if endWord not in st:
16+
return 0
17+
m = len(beginWord)
18+
19+
queue = deque()
20+
queue.append((beginWord, 1))
21+
22+
visited = set()
23+
visited.add(beginWord)
24+
25+
while queue:
26+
cur, step = queue.popleft()
27+
if cur == endWord:
28+
return step
29+
30+
for i in range(m):
31+
for j in range(26):
32+
tmp = cur[:i] + chr(97 + j) + cur[i + 1:]
33+
if tmp not in visited and tmp in st:
34+
queue.append((tmp, step + 1))
35+
visited.add(tmp)
36+
37+
return 0
38+
39+
40+
so = Solution()
41+
# print(so.ladderLength('hit', 'cog', ["hot","dot","dog","lot","log","cog"]))
42+
# print(so.ladderLength('hot', 'dog', ["hot","dog"]))
43+
print(so.ladderLength('hot', 'dot', ["hot", "dot","dog"]))
44+
# print(so.ladderLength('a', 'c', ["a", "b","c"]))
45+
# print(so.ladderLength('hot', 'dog', ["hot", "dog","dot"]))
46+
47+

0 commit comments

Comments
 (0)
Please sign in to comment.