7.10 - hard - 27

126. Word Ladder II:

TLE了,基本想法就是先建立一个hashmap,作为一个图,然后再在图里搜索,结果就TLE了,然后把这个图变成反向图,也就是是从终点出发找起点,同样TLE了。

试试double end bfs来找到图的两点间的最短路径。

class Solution(object):
    def findLadders(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: List[List[str]]
        """
        chars = string.lowercase
        q = [beginWord]
        used = {}
        for w in wordList:
            used[w] = 1
        used[beginWord] = 1
        m = {}
        res = []
        counter = 0
        while q:
            length = len(q)
            counter += 1
            for i in range(length):
                word = q.pop(0)
                used[word] = 0
                m[word] = []
                if word == endWord:
                    # trace back
                    self.search(beginWord, endWord, m, res, [beginWord], counter-1)
                    return res
                for i in range(len(word)):
                    for c in chars:
                        new_word = word[:i] + c + word[i+1:]
                        if new_word != word and new_word in used:
                            m[word].append(new_word)
                            if used[new_word] == 1:
                                used[new_word] -= 1
                                q.append(new_word)
        return res
        
    def search(self, start, end, m, res, cur, counter):
        if counter == 0:
            if start == end:
                res.append(cur[:])
            return

        for word in m[start]:
            cur.append(word)
            counter -= 1
            self.search(word, end, m, res, cur, counter)
            counter += 1
            cur.pop()
                

你可能感兴趣的:(7.10 - hard - 27)