【LeetCode OJ】Word Ladder II

时间:2022-09-01 21:17:34

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. android删除无用资源文件的python脚本

    随着android项目的进行,如果没有及时删除无用的资源时安装包会越来越大,是时候整理一下废弃资源缩小压缩包了,少年! 其实判断一个资源(drawable,layout)是否没有被使用很简单,文件名( ...

  2. 不安装HALCON下安装运行版U盘加密狗驱动

    参考halcon安装指导书 Installation Guide Depending on your operating system, you can install, configure, and ...

  3. 分治法求2n个数的中位数

    问题:设X[0:n-1]和Y[0:n-1]为两个数组,每个数组中含有n个已排好序的数.试设计一个O(logn)时间的分治算法,找出X和Y的2n个数的中位数 思想: 对于数组X[0:n-1]和Y[0:n ...

  4. VS/Visual studio 源代码编辑器里的空处出现点号解决办法

    此原因是不小心按错了键盘上的组合键Ctr+E+S, 再次按Ctr+E+S可消除.

  5. nodejs-日常练习记录-使用express搭建static服务器.

    cd C:\wxg\test\node_demo\myapp nvmw use 0.12.1 node static.js var express = require('express'); var ...

  6. java图片缩放

    package com.rubekid.springmvc.utils; import java.awt.AlphaComposite; import java.awt.Graphics2D; imp ...

  7. luogu3384 【模板】树链剖分

    P3384 [模板]树链剖分 题目描述 如题,已知一棵包含N个结点的树(连通且无环),每个节点上包含一个数值,需要支持以下操作: 操作1: 格式: 1 x y z 表示将树从x到y结点最短路径上所有节 ...

  8. Max Consecutive Ones

    Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1, ...

  9. docker--私有仓库

    私有仓库 有时候使用 Docker Hub 这样的公共仓库可能不方便,用户可以创建一个本地仓库供私人使用. 本节介绍如何使用本地仓库. docker-registry 是官方提供的工具,可以用于构建私 ...

  10. jdk和tomcat的安装

    https://blog.csdn.net/angel_w/article/details/78580528