# 根据单词的每一位来改变,然后每一位变为a->z,判断是否是end是就return 层数+1,
# steps里已经存在则证明走长了,就continue,不存在就添加到steps,并入队作为下一层的元素
# 使用一个set记录单词的使用情况
# 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
#
#
#
# 每次转换只能改变一个字母。
# 转换过程中的中间单词必须是字典中的单词。
#
#
# 说明:
#
#
# 如果不存在这样的转换序列,返回 0。
# 所有单词具有相同的长度。
# 所有单词只由小写字母组成。
# 字典中不存在重复的单词。
# 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
#
#
# 示例 1:
#
# 输入:
# beginWord = "hit",
# endWord = "cog",
# wordList = ["hot","dot","dog","lot","log","cog"]
#
# 输出: 5
#
# 解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
# 返回它的长度 5。
#
#
# 示例 2:
#
# 输入:
# beginWord = "hit"
# endWord = "cog"
# wordList = ["hot","dot","dog","lot","log"]
# 将hit的每一位变成a->z看看是否存在,不存在就加入wordList,并需要一个deepth记录深度
#
# 输出: 0
#
# 解释: endWord "cog" 不在字典中,所以无法进行转换。
# Related Topics 广度优先搜索
# 👍 387 👎 0
# 127.单词接龙
# leetcode submit region begin(Prohibit modification and deletion)
import string
from collections import deque
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
# 根据单词的每一位来改变,然后每一位变为a->z,判断是否是end是就return 层数+1,
# steps里已经存在则证明走长了,就continue,不存在就添加到steps,并入队作为下一层的元素
# 使用一个set记录单词的使用情况
if beginWord == endWord or not beginWord or not wordList:
return 0
word_unused = set(wordList)
dfs_que = deque([beginWord])
steps = {beginWord: 1}
while dfs_que:
deepth = dfs_que.pop()
step = steps[deepth]
for i in range(len(beginWord)):
for each_char in string.ascii_lowercase:
if deepth[i] == each_char: # 如果字母相同就直接比较下个
continue
new_word = deepth[:i] + each_char + deepth[i + 1:]
if new_word == endWord:
return step + 1
if new_word in word_unused:
dfs_que.append(new_word)
word_unused.remove(new_word)
steps[new_word] = step + 1
return 0 # 如果直到最后还没有返回,就返回0