码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 127. Word Ladder

时间:2017-02-20 07:42:25      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:imp   bsp   ini   ons   rdd   class   type   elf   dict   

思路:

 1 class Solution(object):
 2     def __init__(self):
 3         return
 4 
 5     def ladderLength(self, beginWord, endWord, wordList):
 6         """
 7         :type beginWord: str
 8         :type endWord: str
 9         :type wordList: List[str]
10         :rtype: int
11         """
12         from collections import defaultdict, deque
13         queue = deque([[beginWord, 1]])
14         visited = set([beginWord])
15         neighbors = defaultdict(list)
16         for word in wordList:
17             for x in range(len(word)):
18                 token = word[:x] + _ + word[x + 1:]
19                 neighbors[token] += word,
20         while queue:
21             word, length = queue.popleft()
22             if self.wordDist(word, endWord) <= 1:
23                 return length + 1
24             for x in range(len(word)):
25                 token = word[:x] + _ + word[x + 1:]
26                 for ladder in neighbors[token]:
27                     if ladder not in visited:
28                         visited.add(ladder)
29                         queue += [ladder, length + 1],
30         return 0
31 
32     def wordDist(self, wordA, wordB):
33         return sum([wordA[x] != wordB[x] for x in range(len(wordA))])
34 
35 SL = Solution()
36 print(SL.ladderLength(hit, cog, [hot, dot, dog, lot, log]))

 

Leetcode 127. Word Ladder

标签:imp   bsp   ini   ons   rdd   class   type   elf   dict   

原文地址:http://www.cnblogs.com/lettuan/p/6418027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!