Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence 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"]
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.
解题思路:
1/ 广度优先搜索 解决, 遍历过的数据便从 unordered_set中删除
unordered_set 特性: 每个element的查找速度都特别的快
http://www.cplusplus.com/reference/unordered_set/unordered_set/
2/ 通过 make_pair<string , int> 作为队列里面的元素,int 元素存走过的 步数
3/ 刚开始的思路是 通过函数比较每两个单词的 错位 1 ,则 把该词压栈,并将unorder_set中所有错位为1的元素 进入到queue中
该方法超时 ,通过visual 监测 是 通过每个字符a~z变换时间的 30倍
class Solution { public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { queue<pair<string,int>> t; t.push(make_pair(beginWord,1)); if (wordList.empty()) return beginWord == endWord ? 0:0x7ffffff; while (!t.empty()){ string s = t.front().first; int len = t.front().second; t.pop(); if (isnear(s, endWord)) return len+1; string r=ser(wordList,s); while (r != ""){ t.push(make_pair(r,len+1)); r = ser(wordList,s); } } return 0x7fffffff; } bool isnear(const string a,const string b){ if (a.size() != b.size()) return false; int count = 0; for (int i = 0; i < a.size(); i++){ if (a[i] != b[i]){ count++; if (count == 2) return false; } } if (count == 1) return true; else return false; } string ser(unordered_set<string>&a,const string c){ //查找 错位 1 的所有字符 ,返回到一个vector中,并在unordered_set 中删除这些元素 for (auto i = a.begin(); i != a.end();){ int count = 0; string temp = *i; if (c.size() == temp.size()){ for (int j = 0; j < temp.size(); j++){ if (count >= 2) break; else{ if (c[j] != temp[j]) count++; } } if (count == 1){ a.erase(i++); // 注意迭代器的失效问题 return temp; } else i++; } } return ""; } };
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { if (start.empty() || end.empty()) return 0; if (start.size() != end.size()) return 0; if (start.compare(end) == 0) return 1; size_t size = start.size(); queue<string> cur, next; cur.push(start); int length = 2; while (!cur.empty()) { string org = cur.front(); cur.pop(); for (int i = 0; i< size; i++) { string tmp = org; for (char j = 'a'; j <= 'z'; j++) { if (tmp[i] == j) continue; //cout << "tmp = " << tmp << endl; if (tmp.compare(end) == 0) return length; tmp[i] = j; if (dict.find(tmp) != dict.end()) { //cout << "push queue " << tmp << endl; next.push(tmp); dict.erase(dict.find(tmp)); } } } if (cur.empty() && !next.empty()) { swap(cur, next); length++; } } return 0; } };