leetcode Word Ladder
来源:互联网 发布:中国税务网络大学下载 编辑:程序博客网 时间:2024/06/06 01:24
废话少说,先上题:
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(广度优先搜索)来做,比如第一次单词是fit,先找出与fit距离为一的单词,若等于end,则返回,若不是则将该单词加入队列中,重复上述的动作,因为每次扫描都是距离相等的点的集合,若找到则返回,找不到则返回-1,但是,尼玛,爷做的怎么就不能AC呢,fuck,上不能AC的代码:
class Solution {public:queue<string> que;map<string, bool> mapping;bool add(string begin, string end, unordered_set<string>& dict){for (int i = 0; i < begin.size(); i++){for (char j = 'a'; j <= 'z'; j++){string tmp = begin;if (tmp[i] != j){tmp[i] = j;if (!mapping[tmp]){if (dict.find(tmp) != dict.end()){que.push(tmp);if (tmp == end){return true;}mapping[tmp] = true;}}}}}return false;}int bfs(string start, string end, unordered_set<string>& dict){if (add(start, end, dict)){return 2;}int count = 3;int tail = que.size();if (tail == 0){return 0;}while (true){int begin = 0;while (begin < tail){string s = que.front();que.pop();if (add(s, end, dict)){return count;}begin++;}count++;tail = que.size();if (tail == 0){return 0;}}}int ladderLength(string start, string end, unordered_set<string> &dict){for (auto i = dict.begin(); i != dict.end(); i++){mapping[*i] = false;}if (start == end){return 0;}return bfs(start, end, dict);}};
0 0
- [Leetcode][python]Word Ladder/Word Ladder II
- [Leetcode] Word Ladder
- LeetCode: Word Ladder
- leetcode 84: Word Ladder
- [leetcode] word ladder
- 【leetcode】Word Ladder
- 【leetcode】Word Ladder II
- LeetCode - Word Ladder
- LeetCode之Word Ladder
- [LeetCode]Word Ladder
- [LeetCode]Word Ladder II
- [Leetcode]Word Ladder
- [leetcode]Word Ladder
- [leetcode] Word Ladder
- [leetcode] Word Ladder II
- LeetCode-Word Ladder
- LeetCode- Word Ladder
- LeetCode - Word Ladder II
- (64位oracle使用32位的PLSQL)安装64位的oracle数据库软件,使用32位的PLSQL Developer连接方法
- 数字左右翻转
- 内存操作函数:free
- 【C#基础】【控件】课堂笔记 (更新完)
- alexa查看网站使用的web服务器
- leetcode Word Ladder
- 【BZOJ】【P3685】【普通van Emde Boas树】【题解】【vEB树】
- 程序员该如何提高效率
- UVA 10566 Crossed Ladders
- ARX自定义实体常用虚函数explode/worldDraw/transformBy/getOsnapPoints/getGripPoints
- linux设备驱动模型七之driver
- cocos2d-x 2.2.3 ccArray简单分析
- C语言宏定义##连接符和#符的使用
- hive变量传递的源码实现