LintCode 121. Word Ladder II

题目

这里写图片描述
这里写图片描述

思路

1.BFS,找到从end到start的路径,找到每一个单词的层数。
2.DFS,根据每一个单词的层数,按照层数递减的顺序遍历。

代码

import string
class Solution:
    """
    @param: start: a string
    @param: end: a string
    @param: dict: a set of string
    @return: a list of lists of string
    """
    def __init__(self):
        self.res_list = []
    def distanceOne(self, word, word_dict):
        res_list = []
        word = list(word)
        for i, v in enumerate(word):
            for c in string.ascii_lowercase:
                if c != v:
                    word[i] = c
                    str_word = ''.join(word)
                    if str_word in word_dict and word_dict[str_word]:
                        res_list.append(str_word)
                    word[i] = v
        return res_list
    def bfs(self, start, end, word_list):
        distance_dict = {}
        distance_dict[end] = 1
        queue = []
        queue.append(end)
        word_dict = {}
        for word in word_list: 
            word_dict[word] = 1
        word_dict[end] = 0
        while queue:
            word = queue[0]
            queue.pop(0)
            if word == start: return distance_dict
            distance = distance_dict[word]
            next_words = self.distanceOne(word, word_dict)
            for word in next_words:
                word_dict[word] = 0
                distance_dict[word] = distance + 1
                queue.append(word)
        return None
    def dfs(self, end, distance_dict, tmp_list, word, word_dict):
        if word == end:
            self.res_list.append(tmp_list[:])
            return True
        distance = distance_dict[word]
        for word in self.distanceOne(word, word_dict):
            if word in distance_dict and distance_dict[word] == distance - 1:
                word_dict[word] = 0
                tmp_list.append(word)
                self.dfs(end, distance_dict, tmp_list, word, word_dict)
                tmp_list.pop(-1)
                word_dict[word] = 1
    def findLadders(self, start, end, dict):
        # write your code here
        word_list = list(dict)
        if start not in word_list:
            word_list.append(start)
        distance_dict = self.bfs(start, end, word_list)
        if end not in word_list:
            word_list.append(end)
        if not distance_dict: return [[]]
        word_dict = {}
        word_dict[start] = 0
        for word in word_list: 
            word_dict[word] = 1
        self.dfs(end, distance_dict, [start], start, word_dict)
        return self.res_list
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值