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:

  1. Only one letter can be changed at a time
  2. 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
原创粉丝点击