【LeetCode OJ】Word Ladder I
Problem Link:
http://oj.leetcode.com/problems/word-ladder/
Two typical techniques are inspected in this problem:
- Hash Table. One hash set is the words dictionary where we can check if a word is in the dictionary in O(1) time. The other hash set is used to store all visited words we already checked.
- Double-direction BFS. To accelerate the process that finds the shortest path between start word and end word, we need carry on a special BFS from both start word and end word. If there exists a path between start word and end word, then two fronts must meet at some time.
One simple solution for this problem is BFS from the start word, we keep a list of edge words (the last word of each path). Each time, we search all unvisited words next to the edge words, and add these new found words into the new edge list. The program return the length of the path when the end words is reached, or return 0 if no unvisited words can be found.
However, I implemented this BFS but got a TLE. So I adapted a double-direction BFS which may half the running time, and is accepted by the leetcode judge. The algorithm can go as follows.
Let start_front be the list of edge words of BFS paths from the start word
Let end_front be the list of edge words of BFS paths from the end word
Initialize start_front = [start] and end_front = [end]
Start a double direction BFS loop, in each iteration we extend the two fronts as follows:
For each word w in start_front
Find all transformable words of w those are not visited yet
Let all new found words be the new start_font, return 0 if no new words found
If two fronts meet, then return the number of transforms
For each word w in end_front
Find all transformable words of w those are not visited yet
Let all new found words be the new end_front, return 0 if no new words found
If two fronts meet, then return the number of transforms
The following code is the python implementatation which is accepted by leetcode.com.
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
"""
Suppose start, end, and all words in dict are of the same length.
Then we apply BFS from both start and end, and keep track of the two front edges.
If the two front meet, then there is a path from start to end.
The algorithm can go as follows.
1) Let start_front be the list of words on the edge BFS from start word;
2) Let end_front be the list of words on the edge BFS from end word;
3) Initialize start_front = [start] and end_front = [end]
4) Start a loop where each iteration we do extend two fronts and check if they meet:
1a) Extend the start front to unvisited words
1b) If the start front cannot be extent, it means there is no path between start and end,
then return 0.
1c) If the two fronts meet, then return (transform_number + 1)
2a) Extend the end front to unvisited words
2b) If the end front cannot be extent, then return 0
2c) If the two front meet, then return (transform_number + 1)
"""
# Special cases
if start == end:
return 1 # The length of words
WORD_LENGTH = len(start) # Initialize the two fronts
start_front = [start]
end_front = [end] # Initialize the number of transforms
counter = 0 # Initialize the set of visited words
visited = set()
visited.add(start)
visited.add(end) # Extend the two fronts and check if they can meet
while True:
# Extend the start front
new_front = []
# Suppose the start front can extend
counter += 1
# Check all unvisited words transformed from the start front
for w in start_front: # Each word in the start front
for i in xrange(WORD_LENGTH): # Each character in the word
for candidate in [w[:i]+chr(97+c)+w[i+1:] for c in xrange(26)]:
# Check if two fronts can meet
if candidate in end_front:
return counter + 1
# Find all unvisited words from the front and add them as new front
if candidate in dict and candidate not in visited:
new_front.append(candidate)
visited.add(candidate)
# Check if there exists any word for the new front
if new_front:
start_front = new_front
else:
return 0 # Extend the end front
new_front = []
# Suppose the end front can extend
counter += 1
# Check all unvisited words transformed from the end front
for w in end_front: # Each word in the end front
for i in xrange(WORD_LENGTH): # Each character in the word
for candidate in [w[:i]+chr(97+c)+w[i+1:] for c in xrange(26)]:
# Check if two fronts can meet
if candidate in start_front:
return counter + 1
# Find all unvisited words from the front and add them as new front
if candidate in dict and candidate not in visited:
new_front.append(candidate)
visited.add(candidate)
# Check if there exists any word for the new front
if new_front:
end_front = new_front
else:
return 0
【LeetCode OJ】Word Ladder I的更多相关文章
- 【LeetCode OJ】Word Ladder II
Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...
- 【LeetCode OJ】Word Break II
Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...
- 【LeetCode OJ】Word Break
Problem link: http://oj.leetcode.com/problems/word-break/ We solve this problem using Dynamic Progra ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Validate Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...
- 【LeetCode OJ】Recover Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...
- 【LeetCode OJ】Same Tree
Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...
- 【LeetCode OJ】Symmetric Tree
Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...
随机推荐
- hduoj----1142A Walk Through the Forest(记忆化搜索+最短路)
A Walk Through the Forest Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Jav ...
- Unique Paths [LeetCode]
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...
- A New Tetris Game
时间限制(普通/Java):1000MS/10000MS 运行内存限制:65536KByte 总提交: 40 测试通过: 12 描述 曾经,Lele和他姐姐最喜欢,玩得最 ...
- poj1129 Channel Allocation(染色问题)
题目链接:poj1129 Channel Allocation 题意:要求相邻中继器必须使用不同的频道,求需要使用的频道的最少数目. 题解:就是求图的色数,这里采用求图的色数的近似有效算法——顺序着色 ...
- c++ boost 汉字和模式串混用的例子
*=============================================================== * Copyright (C) All rights reserved ...
- WPF布局的6种面板
WPF用于布局的面板主要有6个,StackPanel(栈面板).WrapPanel(环绕面板).DockPanel(停靠面板).Canvas(画布).Grid(网格面板)和 UniformGrid(均 ...
- [转]Java8-本地缓存
这里我将会给大家演示用ConcurrentHashMap类和lambda表达式实现一个本地缓存.因为Map有一个新的方法可以在key为Null的时候自动计算一个新的value值.非常完美的实现cach ...
- 使用PL/SQL连接远程的Oracle数据库
PL/SQL不仅可以连接本机的oracle数据库.也可以连接远程的数据库. 需要修改一个文件:在本机oracle 数据库的安装目录下找到这个文件: /oracle/ora92/network/admi ...
- .net调用存储过程碰到的一个问题
问题描述 报错信息如下: Execution of user code in the .NET Framework is disabled. Enable "clr enabled" ...
- K需要修改的内容
1.需要保存默认案件,所有相关的页面的Title都要显示默认按键信息. 2.播放器需要调整,左侧的是播放信息,用户选择:案件/设备/然后就把该目录下的文件都展示出来.用户选择的时候马上进行播放.右侧有 ...