​LeetCode刷题实战126:单词接龙 II

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 单词接龙 II,我们先来看题面:

https://leetcode-cn.com/problems/word-ladder-ii/

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time

Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

Return an empty list 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.

题意

给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:

每次转换只能改变一个字母。

转换后得到的单词必须是字典中的单词。

说明:

如果不存在这样的转换序列,返回一个空列表。

所有单词具有相同的长度。

所有单词只由小写字母组成。

字典中不存在重复的单词。

你可以假设 beginWord 和 endWord 是非空的,且二者不相同。

样例



示例 1:

输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

输出:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]

示例 2:

输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

输出: []

解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。

解题

先利用BFS从endWord到beginWord得到满足连通要求的单词到endWord的最短距离dist。

再利用DFS遍历从beginWord到endWord的得到满足dist的所有单词序列。(注:这里DFS利用递归来做,不能用栈,因为要得到所有满足要求的单词序列)

class Solution:
    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: 
        wordList=set(wordList)
        wordList.add(beginWord)
        #wordList.append(beginWord)
        dist=self.bfs(endWord,wordList)
        res=[]
        self.dfs(beginWord,endWord,wordList,dist,[beginWord],res)
        return res
    
    #bfs记录点到终点的最短距离:end -> start 
    def bfs(self,begin,wordList):
        dist={}
        dist[begin]=0
        queue=[begin]
        while queue:
            L=len(queue)
            for _ in range(L):
                word=queue.pop(0)
                for w in self.nextWord(word,wordList):
                    if w not in dist:
                        dist[w]=dist[word]+1
                        queue.append(w)
        return dist
        

    #利用递归来记录路径:从start -> end
    def dfs(self,curr,end,wordList,dist,path,res):
        if curr==end:
            res.append(list(path))
        for w in self.nextWord(curr,wordList):
            if dist[w]==dist[curr]-1:
                path.append(w)
                self.dfs(w,end,wordList,dist,path,res)
                path.pop()
                
        
    def nextWord(self,word,wordList):
        res=[]
        for i in range(len(word)):
            for letter in "abcdefghijklmnopqrstuvwxyz":
                next_=word[0:i]+letter+word[i+1::]
                if next_!=word and next_ in wordList:
                    res.append(next_)
        return res

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-120题汇总,希望对你有点帮助!

LeetCode刷题实战121:买卖股票的最佳时机

LeetCode刷题实战122:买卖股票的最佳时机 II

LeetCode刷题实战123:买卖股票的最佳时机 III

LeetCode刷题实战124:二叉树中的最大路径和

LeetCode刷题实战125:验证回文串

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值