[LeetCode]Word Ladder

题目描述:

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:

Only one letter can be changed at a time

Each intermediate word must exist in the dictionary

For example,

Given:

start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",

return its length 5.

Note:

Return 0 if there is no such transformation sequence.

All words have the same length.

All words contain only lowercase alphabetic characters.

题目大意:

给定两个单词(beginWord 和 endWord),以及一个字典,寻找从 beginWord 到 endWord 的最短转换序列的长度,满足约束条件:

每次只能改变一个字母

每一个得到的单词必须存在于字典中

例如,给定:

start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

最短的转换序列为:"hit" -> "hot" -> "dot" -> "dog" -> "cog",

返回其长度5。

注意:

如果不存在这样的转换序列,返回0。

所有的单词都是等长的。

所有的单词都只包含小写字母。

解题思路:

方法I:BFS(广度优先搜索)

将wordDict中单词word的每一个字母使用下划线“_”代替,得到wordKey

可以构造wordKey -> word的映射,记为neighbors

for word in wordDict:
    for x in range(len(word)):
        token = word[:x] + '_' + word[x+1:]
        neighbors[token] += word,

在BFS的执行过程中,将当前单词word的每一位以下划线“_”代替,

在neighbors字典中查找其“相邻”单词(只改变一个字母得到的单词)

Python代码:

class Solution:
    # @param {string} beginWord
    # @param {string} endWord
    # @param {set<string>} wordDict
    # @return {integer}
    def ladderLength(self, beginWord, endWord, wordDict):
        from collections import defaultdict, deque
        queue = deque( [ [beginWord, 1] ] )
        visited = set( [ beginWord ] )
        neighbors = defaultdict(list)
        for word in wordDict:
            for x in range(len(word)):
                token = word[:x] + '_' + word[x+1:]
                neighbors[token] += word,
        while queue:
            word, length = queue.popleft()
            if self.wordDist(word, endWord) <= 1:
                return length + 1
            for x in range(len(word)):
                token = word[:x] + '_' + word[x+1:]
                for ladder in neighbors[token]:
                    if ladder not in visited:
                        visited.add(ladder)
                        queue += [ladder, length + 1],
        return 0
    def wordDist(self, wordA, wordB):
        return sum([wordA[x] != wordB[x] for x in range(len(wordA))])

方法II:双向BFS

从起点beginWord和终点endWord同时进行广度优先搜索,执行速度较方法I更快

Python代码:

class Solution:
    # @param {string} beginWord
    # @param {string} endWord
    # @param {set<string>} wordDict
    # @return {integer}
    def ladderLength(self, beginWord, endWord, wordDict):
        from collections import defaultdict, deque
        qf = deque( [ [beginWord, 0] ] )
        qe = deque( [ [endWord, 0] ] )
        sf = { }
        se = { }
        neighbors = defaultdict(list)
        for word in wordDict:
            for x in range(len(word)):
                token = word[:x] + '_' + word[x+1:]
                neighbors[token] += word,
        while qf or qe:
            if qf:
                word, length = qf.popleft()
                if word in se :
                    return length + se[word] + 1
                for x in range(len(word)):
                    token = word[:x] + '_' + word[x+1:]
                    for ladder in neighbors[token]:
                        if ladder not in sf:
                            sf[ladder] = length + 1
                            qf += [ladder, length + 1],
            if qe:
                word, length = qe.popleft()
                if word in sf :
                    return length + sf[word] + 1
                for x in range(len(word)):
                    token = word[:x] + '_' + word[x+1:]
                    for ladder in neighbors[token]:
                        if ladder not in se:
                            se[ladder] = length + 1
                            qe += [ladder, length + 1],
        return 0

 

本文链接:http://bookshadow.com/weblog/2015/08/17/leetcode-word-ladder/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论