单词变换距离 Word Ladder (图的最短路径)
2014-02-28 20:15
441 查看
问题: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 =
end =
dict =
As one shortest transformation is
return its length
思路:寻找邻接点的方法有两个:一个是遍历字典集合,分别判断是否是邻接的。另一个是根据字母表直接构造邻接的元素,然后判断其是否在字典集合中。当字典中数据个数较小时选第一个;当字典中数据个数多时选第二个。
这是一个无权图的路径寻找问题。可以用DFS、也可以用BFS。虽然都可以用,但是实际上,DFS和BFS在求解的时间复杂度上差别巨大。
BFS每一层扫描都把所有能直接到达的字符串拿到,并且一定会在最近的层数被扫描到。所以BFS能更快的找到最短路径,并且遍历的次数不会太多。而DFS则不适合寻找最短路径。所以无权图的最短路径问题优先选择BFS。
问题扩展:单词变换路径 Word Ladder II
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.
思路:寻找邻接点的方法有两个:一个是遍历字典集合,分别判断是否是邻接的。另一个是根据字母表直接构造邻接的元素,然后判断其是否在字典集合中。当字典中数据个数较小时选第一个;当字典中数据个数多时选第二个。
这是一个无权图的路径寻找问题。可以用DFS、也可以用BFS。虽然都可以用,但是实际上,DFS和BFS在求解的时间复杂度上差别巨大。
BFS每一层扫描都把所有能直接到达的字符串拿到,并且一定会在最近的层数被扫描到。所以BFS能更快的找到最短路径,并且遍历的次数不会太多。而DFS则不适合寻找最短路径。所以无权图的最短路径问题优先选择BFS。
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { queue<string> que; queue<int> level;//用来记录当前所在的层次 int cur = 2; level.push(cur); que.push(start); dict.insert(end); while(!que.empty()) { string now = que.front(); que.pop(); cur = level.front(); level.pop(); for(int i=0;i<start.length();i++) { for(int j=0;j<26;j++) { string next = now; next[i] = 'a' + j; if(now != next && dict.find(next) != dict.end()) { if(next == end) return cur; que.push(next); level.push(cur+1); dict.erase(next); } } } } return 0; } };
问题扩展:单词变换路径 Word Ladder II
相关文章推荐
- 单词变换路径 Word Ladder II
- 127. Word Ladder 单词间的最短路径
- LeetCode 245. Shortest Word Distance III (最短单词距离之三) $
- [LeetCode] Shortest Word Distance 最短单词距离
- LeetCode Word Ladder 找单词变换梯
- [LeetCode]Word Ladder 字符串的最短转换距离 (Dijkstra)
- Word Ladder II——找出两词之间最短路径的所有可能
- LeetCode-243:Shortest Word Distance (单词最短距离)
- LeetCode 244. Shortest Word Distance II(最短单词距离)
- [LeetCode] 245. Shortest Word Distance III 最短单词距离 III
- LeetCode 245. Shortest Word Distance III(最短单词距离)
- [LeetCode] 244. Shortest Word Distance II 最短单词距离 II
- [LeetCode] Shortest Word Distance III 最短单词距离之三
- [LeetCode] Shortest Word Distance II 最短单词距离之二
- [Leetcode] word ladder 单词阶梯
- LeetCode-Word Ladder-单词梯-BFS构图
- PAT程序设计练习——甲级1003(任意两个城市最短距离、Floyd最短路径算法)
- 给出两个单词,找到它们的最短距离
- _DataStructure_C_Impl:在图G中求距离顶点v0最短路径为k的所有顶点
- 最短路径之 floyd (适用于 多点距离)