LeetCode--word ladder(python)

题目:

给定一个开始字符串beginWord 如 ‘hit’,结束字符串endWord如‘cog’,字符串字典wordlist 如 ["hot","dot","dog","lot","log","cog"]。从开始字符串开始,要求每次只能改变一个字符,求经过wordlist到达endWord的最短路径

解题思路:

考虑到最短路径,用djistra算法,从开始字符串出发,找到该字符串改变一个字符后可以到达wordlist中的所有字符串。再从新到达的字符串列表出发,计算一步之后可以到达wordlist中之前未到达的所有字符串。经过多次循环,直到新到达的字符串中包含结束字符串,返回当前步数即可。

注意:

这是一个非常卡时间的题目。需要将原始的字符串字典wordlist存为python中的字典格式,减少搜索的复杂度(从n到1)

代码如下(leetcode中AC):

class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        character = 'abcdefghijklmnopqrstuvwxyz'
        def dijkstra(new_list,unreached_list,endWord,count):
            if unreached_list==[] or new_list==[]:
                return 0
            count = count + 1
            list_return = []
            for i in range(len(new_list)):
                for j in range(len(new_list[i])):
                    for k in character:
                        temp = new_list[i]
                        tmp1 = temp[:j]
                        tmp2 = temp[j+1:]
                        temp = tmp1+k+tmp2
                        if temp==new_list[i][j]:
                            continue
                        else:
                            if temp in unreached_list:
                                list_return.append(temp)
                                if temp==endWord:
                                    return count
                                del unreached_list[temp]
            return dijkstra(list_return,unreached_list,endWord,count)
        begin = []
        begin.append(beginWord)
        dict_unreach = {}
        for i in range(len(wordList)):
            if wordList[i] not in dict_unreach:
                dict_unreach[wordList[i]] = 1
        return dijkstra(begin,dict_unreach,endWord,1)



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值