lc 126. Word Ladder II

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

1.正向搜索,反向穷举答案。这样才能使运行时间严格等于答案规模,避免爆炸💥。

2.第一次尝试用generator,感觉很好。

3.预处理三步走:  a.生成所有邻近词  b.生成所有list中的邻近关系  c.梳理出前后路径,作为方向,

上面的bc两步应该有大佬可以并坐一步?

class Solution:
    def gene(self,w): # 一个美好的generator!!!给定一个初始化的词汇w,生成所有w“之上”的邻近词汇,来保证单向性。opq之上有opz,xyz,zzz等,但是没有opa
        for i in range(len(w)):
            for j in range(ord(w[i])-ord('a')+1,26):
                yield w[:i]+chr(ord('a')+j)+w[i+1:]

    def neighbor(self,w,d):
        for ns in self.gene(w): #由gene生成neighbors
            if ns in d:
                d[w].append(d[ns][0])
                d[ns].append(d[w][0])

    def ans_from(self,w,to,end):
        if w==end:
            return [[end]]
        ans=[]
        for t in to[w]:
            ans+=[i+[w] for i in self.ans_from(t,to,end) if i!=None] # 递归!!!注入灵魂
        return ans

    def findLadders(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: List[List[str]]
        """
        if beginWord not in wordList:
            wordList.append(beginWord)
        d={}
        for i,w in enumerate(wordList):
            d[w]=[i]
        if endWord not in d:
            return []
        for w in wordList:
            self.neighbor(w,d)
        # print(d)

        bel=[0]*len(wordList)
        bel[d[beginWord][0]]=-1
        bel[d[endWord][0]]=1

        to=[[]for i in range(len(wordList))]
        next=set([d[beginWord][0]]) #用set避免多次加入

        while len(next)>0:
            next_t=set()
            for c in next:
                for i in range(1,len(d[wordList[c]])):
                    # print(i)
                    # print(c)
                    ni=d[wordList[c]][i]
                    if bel[ni]!=-1:
                        to[c].append(ni)
                        next_t.add(ni)
            for x in next_t: # 整个存入后再加next_t因为可以从不同的节点到达当前点
                bel[x]=-1
            next=next_t
        # print(wordList)
        print(to)
        return [[wordList[pp] for pp in p][::-1] for p in self.ans_from(d[beginWord][0],to,d[endWord][0])]

 

posted @ 2019-01-17 16:49  Cloud.9  阅读(201)  评论(0编辑  收藏  举报