leetcode -- Word Ladder I & II -- II没有理解

Word Ladder

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

这里思路就是BFS, DFS 太慢。对于start word,其可能的下一个word应该是两个for循环,外层是对start word的每个将要替换的字母index的循环,内层是循环25个字母(排除掉当前字母),然后再看是否在wordList里面,如果在的话,就是BFS下一层的candidate,因为是求最短的路径,所以如果对于start word有两个或者以上的candidates,这些candidates记为 set K,那么再下一层的搜索范围只可能在wordList - K的这些word中。例如,K = {w1, w2}, 如果w1再下一层还可以搜索到w2,那么就跟直接从start word到w2的搜索结果一样,但是长度要多1.所以,其实只要在每次循环到word在wordlist中的话,就可以入queue,然后在wordlist中删除这个word。

思路参考http://www.cnblogs.com/zuoyuan/p/3765858.html
http://yucoding.blogspot.hk/2013/08/leetcode-question-127-word-ladder.html
http://liangju.li/post/leetcode/2014-07-03
http://chaoren.is-programmer.com/posts/43039.html

    def ladderLength(self, start, end, dict):
        dict.add(end)
        q = []
        q.append((start, 1))
        while q:
            curr = q.pop(0)
            currword = curr[0]; currlen = curr[1]
            if currword == end: return currlen
            for i in range(len(start)):
                part1 = currword[:i]; part2 = currword[i+1:]
                for j in 'abcdefghijklmnopqrstuvwxyz':
                    if currword[i] != j:
                        nextword = part1 + j + part2
                        if nextword in dict:
                            q.append((nextword, currlen+1)); 
                            dict.remove(nextword)
        return 0

Word Ladder II

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

很难,leetcode通过率最低的题目。

参考http://chaoren.is-programmer.com/posts/43039.html

其中 level表示的是BFS 第i层待搜索的nodes or candidates,其实就是queue的一段。然后next_level就是下一层的nodes or candidates. next_level 还记录了这一层每个node的父节点。然后记录到了parents中。
parents保存了所有path的信息,每个node的父节点。

# 2015-06-18  Runtime: 712 ms
class Solution:
    # @param start, a string # @param end, a string # @param dict, a set of string # @return a list of lists of string def findLadders(self, start, end, dic): # thanks to https://leetcode.com/discuss/24191/defaultdict-for-traceback-and-easy-writing-lines-python-code dic.add(end) level = set([start])#这里是把一个list转换为set # key is word, value is parent word, e.g. {'hot': set(['hit']), 'cog': set(['log', 'dog'])} # In each level, defaultdict(set) can remove duplicates, first we need to get parent dictionary parents = collections.defaultdict(set) while level and end not in parents: next_level = collections.defaultdict(set) for word in level: for char in 'abcdefghijklmnopqrstuvwxyz': for i in xrange(len(start)): childWord = word[:i] + char + word[i+1:] if childWord in dic and childWord not in parents: next_level[childWord].add(word) level = next_level parents.update(next_level) # then according parent dictionary, build result from end word to start word res = [[end]] while res and res[0][0] != start: res = [[p] + r for r in res for p in parents[r[0]]] return res

没完全理解。

参考:http://yucoding.blogspot.hk/2014/01/leetcode-question-word-ladder-ii.html

你可能感兴趣的:(LeetCode)