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. 6/6 Sprint2 看板和燃尽图

    页面头部的修改  

  2. html 标签总结

    <q>标签,短文本引用 例如“聪明秀出为之英,胆略过人为之雄.” <blockquote>标签,长文本引用 <blockquote>标签的解析是缩进样式. 没有HT ...

  3. UNIX高级环境编程学习

    1-5实例 控制字符:ctrl + 另一个键.control + D或者^D是默认的文件结束符(EOF字符).

  4. Hibernate映射之实体映射

    1.使用@注解配置实体类 实体类一般有ID.普通属性.集合属性等,分别对应数据库的主键.普通列.外键.@注解配置中,实体类用@Entity注解,用@Table指定对应的数据表,用@Id配置主键,用@C ...

  5. spring的bean管理

    1.所有的类都可以交给Spring管理 2.如何把一个类交给bean管理? (1)配置applicationContext.xml (2)在xml中写入bean节点配置要交给bean管理的类 3.程序 ...

  6. web开发常用的js验证,利用正则表达式验证邮箱、手机、身份证等输入

    正则表达式验证 //邮箱 \-])+\.)+([a-zA-Z0-]{,})+$/; email = document.getElementById("email").value; ...

  7. JavaWeb chapter 1 http协议

    1.  静态web和动态web的区别: 静态web和动态web最本质的区别是静态web是无法进行数据库操作,而动态web是可以进行数据库操作的.动态web的最大特点就是具有交互性,所谓交互性就是服务器 ...

  8. HookIAT的启动程序

    // 启动程序.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> #include &l ...

  9. 常州培训 day1 解题报告

    第一题:(骗分容易,AC难.) 题目大意: 给出一个字符串,找出满足条件A的区间的个数.A:字符A,B,C的出现次数相同. 都出现0次也算,区间的长度可以是0(就是只有一个数).30% |S| ≤ 1 ...

  10. 利用K2和Microsoft Dynamics CRM构建业务App的5大理由

    Microsoft Dynamics CRM提供了一个绝佳的客户关系管理平台,使您能够创建各种以客户为中心的解决方案.然而,通过将K2的企业业务流程功能与Microsoft Dynamics CRM相 ...