您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:Word Ladder II(126)

2016-06-11 22:11 435 查看

题目

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time

Each intermediate word must exist in the word list

For example,

Given:

beginWord = “hit”

endWord = “cog”

wordList = [“hot”,”dot”,”dog”,”lot”,”log”]

Return

[

[“hit”,”hot”,”dot”,”dog”,”cog”],

[“hit”,”hot”,”lot”,”log”,”cog”]

]

算法

题意说明:从start变换到end,途中只能经过字典中的单词,每次只允许差一个字母。

要求输出所有变换路径。

分析:题倒是不难,但时间卡的特别紧。

常规方法:BFS搜索,节点的数据结构包含:当前单词、记录变换路径的hash表、记录变换路径的ArrayList。搜索所有和当前单词只差一个字母的单词,查询新单词是否在字典中同时是否已经存在于变换路径中,如果在字典中同时不在已有的变换路径中,把新单词放入队列,继续BFS。代码如下,可惜大数据超时。

待续

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: