Word Ladder

update Jul 21, 2017 16:45

LintCodearrow-up-right

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  • Only one letter can be changed at a time

  • Each intermediate word must exist in the dictionary

    Notice

  • Return 0 if there is no such transformation sequence.

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

Example

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Basic Idea:

这道题目其实是一个隐式图搜索的题目,要求的是最短的变化路径长度,所以首选BFS。 如上就是这个图的例子(来自jiuzhang)。 实现的基本思路就是每次考虑距离当前word只有一个编辑距离的dict中的词,如果还没有visit过,则加入queue,分层bfs,记录step数。 细节: 在生成 1 编辑距离的neighbors时,如果对所有dict中的单词逐一检查,是O(#words in dict * length) 的时间复杂度,所以这里采用生成所有 1 编辑距离的变化的单词,然后查看dict中是否有这个词,是O(26 * length^2)的复杂度,在dict中word很多而长度较短的时候,更有优势。

python code:

java code:

update 2018-06-23 22:07:35

Update C++ BFS Solution

update Sep 9, 2019

Update, Leetcode version

Leetcode 上的版本和lintcode有些许出入,但只需要略加修改即可:

Java Code:

C++ Code

有一点可以优化的地方,其实我们不需要另外使用一个 visited set,而是可以利用 wordSet(dict),每当我们将一个neighbor放入queue,我们就在wordset中将其去掉。

Last updated