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

leetcode 126. Word Ladder II

时间:2016-10-18 02:18:34      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

 1 import string
 2 import collections
 3 
 4 class Solution(object):
 5     def findLadders(self, begin, end, words_list):
 6         ‘‘‘删除起至单词‘‘‘
 7         words_list.discard(begin)
 8         words_list.discard(end)
 9 
10         ‘‘‘根据tree递归构造路径‘‘‘
11         def construct_paths(source, dest, tree):
12             if source == dest: 
13                 return [[source]]
14             return [[source] + path for succ in tree[source]
15                                     for path in construct_paths(succ, dest, tree)]
16         
17         ‘‘‘广度优先遍历分层搜索‘‘‘
18         def bfs_level(this_lev, endw, tree, words_set):
19             if not this_lev: return False
20             for word in (this_lev):
21                 words_set.discard(word)
22             next_lev, done = set(), False
23             while this_lev:
24                 word = this_lev.pop()
25                 for c in string.ascii_lowercase:
26                     for index in range(len(word)):
27                         neigh = word[:index] + c + word[index+1:]
28                         if neigh == endw:
29                             done = True
30                             tree[word].append( neigh )
31                         if not done and neigh in words_set:
32                             next_lev.add(neigh)
33                             tree[word].append( neigh )
34             return done or bfs_level(next_lev, endw, tree, words_set)
35 
36         
37         tree, path, paths = collections.defaultdict(list), [begin], []
38         is_found = bfs_level(set([begin]), end, tree, words_list)
39         return construct_paths(begin, end, tree)

 

leetcode 126. Word Ladder II

标签:

原文地址:http://www.cnblogs.com/muchrooms/p/5971858.html

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