Problem Link:

http://oj.leetcode.com/problems/word-ladder-ii/

Basically, this problem is same to Word Ladder I, which uses a double-direction BFS. However, the difference is that we need to keep track of all paths during the double-direction BFS in order to output all possible shortest paths from the start word to the end word. To do this, we use the build-in dictionary strucutre in python. After the BFS, we need another normal BFS from the start word following the path dictionary, and return all paths reaching the end word.

Python performance issue. During the constructing the path dictionary, we need to check whether the key already exists. We can use dict.has_key() or key in dict.keys(), however both ways get a TLE by oj.leetcode.com. In this case, we can use dict.setdefault(key, default_value) or try...except... clause to accelerate such operations.

class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def findLadders(self, start, end, dict):
"""
Similar to solving WordLadder 1, we use a double-direction BFS.
However, instead of only storing the last word of each path (front edges),
we need to store the entire path.
In the code for solving WordLadder 1,
we check two fronts meet during extending the paths,
but this problem asks for all possible shortest path,
so we need to extend all paths and then check all pairs of paths from start and end.
"""
# Special cases
if start == end:
return [start] # The length of words
WORD_LENGTH = len(start) # New words in one step
new_words = set() # Initialize the set of visited words
start_front = set()
start_front.add(start)
start_visited = set()
start_visited.add(start) end_front = set()
end_front.add(end)
end_visited = set()
end_visited.add(end) # Add end to the dictionary
dict.add(end) # Traverse map
next_words = {} meet = False
# Extend the two fronts and check if they can meet
while not meet:
# Extend the start front
new_words.clear()
for w in start_front:
next_words[w] = []
for i in xrange(WORD_LENGTH):
for candidate in [w[:i]+chr(97+c)+w[i+1:] for c in xrange(26)]:
if candidate in dict and candidate not in start_visited:
next_words[w].append(candidate)
new_words.add(candidate)
if new_words:
# Update visited words
start_visited.update(new_words)
start_front = new_words.copy()
else:
return [] # Check if two fronts meet
if start_front & end_front:
break # Extend the end front
new_words.clear()
for w in end_front:
for i in xrange(WORD_LENGTH):
for candidate in [w[:i]+chr(97+c)+w[i+1:] for c in xrange(26)]:
if candidate in dict and candidate not in end_visited:
next_words.setdefault(candidate, []).append(w)
#try:
# next_words[candidate].append(w)
#except:
# next_words[candidate] = [w]
new_words.add(candidate)
if new_words:
end_visited.update(new_words)
end_front = new_words.copy()
else:
return []
# Check if two fronts meet
if start_front & end_front:
break
# BFS from start to end
res = []
path = [[start]]
while res == []:
new_path = []
for p in path:
try:
for w in next_words[p[-1]]:
new_path.append(p+[w])
if w == end:
res.append(p+[w])
except:
pass
path = new_path
# Return all paths in res
return res

【LeetCode OJ】Word Ladder II的更多相关文章

  1. 【LeetCode OJ】Word Ladder I

    Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...

  2. 【LeetCode OJ】Word Break II

    Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...

  3. 【LeetCode OJ】Word Break

    Problem link: http://oj.leetcode.com/problems/word-break/ We solve this problem using Dynamic Progra ...

  4. 【LeetCode OJ】Path Sum II

    Problem Link: http://oj.leetcode.com/problems/path-sum-ii/ The basic idea here is same to that of Pa ...

  5. 【LeetCode OJ】Palindrome Partitioning II

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...

  6. 【LEETCODE OJ】Single Number II

    Problem link: http://oj.leetcode.com/problems/single-number-ii/ The problem seems like the Single Nu ...

  7. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

  8. 【LeetCode 229】Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...

  9. 【leetcode刷题笔记】Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

随机推荐

  1. JS禁止右键

    function cancelMouse(){return false;}document.oncontextmenu = cancelMouse;

  2. Java 集合系列 07 List总结(LinkedList, ArrayList等使用场景和性能分析)

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  3. VS复习 -- if···else和if···else嵌套语句

    注意:理清逻辑,画出逻辑分支图,理清思路 1.if语句 2.if...else语句 3.if..else if...else static void Main(string[] args) { Con ...

  4. 用js实现返回上一页

    <a href="javascript :;" onClick="javascript :history.back(-1);">返回上一页</ ...

  5. 如何为Kafka集群选择合适的Partitions数量

    转载:http://blog.csdn.net/odailidong/article/details/52571901 这是许多kafka使用者经常会问到的一个问题.本文的目的是介绍与本问题相关的一些 ...

  6. PHP换行符详解 PHP_EOL,<br />

    1.PHP_EOL:用于文本的换行符,经常用于日志文件记录.可以解决: 在windows中\r\n是换行在Mac中\r是换行在Liunx中\n是换行 不统一的问题. 2. <br /> : ...

  7. Computer Science Courses – Yan Yan

    CS: Compilers / Programming Languages Course Title Fundamentals of C++ Language Programming Textbook ...

  8. iBatisSQL中prepend的问题

    是前向声明还是后向声明? 官方文档那个给出:“the overridable SQL part that will be prepended to the statement”.可见是前向声明. -- ...

  9. 使用WebView视图显示网页-----迷你浏览器

    Android提供了WebView组件,表面上来看,这个组件与普通ImageView差不多,但实际上,这个组件的功能要强大得多,WebView组件本身就是一个浏览器实现,它的内核基于开源WebKit引 ...

  10. 检索 COM 类工厂中 CLSID 为 {10020200-E260-11CF-AE68-00AA004A34D5} 的组件时失败,解决方法如下:

    检索 COM 类工厂中 CLSID 为 {10020200-E260-11CF-AE68-00AA004A34D5} 的组件时失败,解决方法如下: 第 一步:首先将msvcr71.dll,  SQLD ...