【LeetCode每天一题】 Word Ladder(单词阶梯)

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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

思路

  我先大概描述一下这个题目到底是什么意思,题目中给了一个开始单词,一个结束单词和一个单词列表。题目要求我们根据开始的单词利用单词列表一步一步将其改变成结束单词。这个过程经历了几次就是结果。可以结合例子来进行理解。看到这个题目我没能做出来。看了答案之后明白了大概的解法。思路就是我们先对单词列表中每一个单词进行预处理(就是对单词每一位分别进行替换成*,然后作为键存储到字典中,值是一个列存储的是和键(除了*部分)匹配的单词)。这样在对单词列表初始化之后我们可以得到一个字典。然后我们从开始单词开始,对每一位进行*替换,然后在字典中进行查找到相应的列表,并对字典中的列表进行遍与开始单词匹配的单词。这样一直到最后我们可以得到结果。
解决代码

 
 
 1 from collections import defaultdict
 2 class Solution(object):
 3     def ladderLength(self, beginWord, endWord, wordList):
 4         """
 5         :type beginWord: str
 6         :type endWord: str
 7         :type wordList: List[str]
 8         :rtype: int
 9         """
10 
11         if endWord not in wordList or not endWord or not beginWord or not wordList:   # 异常情况的判断
12             return 0
13         L = len(beginWord)
14 
15         tem_dict = defaultdict(list)         # 设置字典
16         for word in wordList:           # 对单词列表进行初始化
17             for i in range(L):          # 对其中每一个单词进行进行处理
18                 tem_dict[word[:i] + "*" + word[i+1:]].append(word)
19 
20         queue = [(beginWord, 1)]         # 设置一个队列辅助空间
21         visited = {beginWord: True}       # 设置一个记录已经访问过的单词
22         while queue:                    # 开始查找
23             curword, level = queue.pop(0)       # 弹出队列头的元素
24             for i in range(L):                    # 对当前单词进行替换用来在字典中进行查找
25                 t_word = curword[:i] + "*" + curword[i+1:]
26 
27                 for word in tem_dict[t_word]:        # 对匹配的单词列表进行遍历
28                     if word == endWord:         # 如果当前遍历单词和结果单词相等直接返回结果
29                         return level + 1
30                     if word not in visited:     # 查看该单词是否已经被访问过。
31                         visited[word] = True
32                         queue.append((word, level + 1))
33                 tem_dict[t_word] = []
34         return 0        # 说明为找到
 

转载于:https://www.cnblogs.com/GoodRnne/p/10914067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值