Word Ladder 题解
题目来源:Word Ladder
>
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
For 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.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.解题思路:
bfs
用BFS搜索,记录从开始到当前路径长度。注意遍历map/set删除满足条件的element的写法。第一个用BFS搜索到的肯定是最短的之一。DFS则不是哦。
悲剧的是,上面的过不了~ testcase中dict太大,而word相对较短,去从dict去搜索相邻的单词,耗时太久。改为变动word中的每一个字符(26个一个一个试),然后再去dict中判断是否存在。这样就能AC。ref, 代码如下:
Last updated
Was this helpful?