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 transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5
坑的地方在于 :
for(int i=0;i<q.size();i++)
for(int i=q.size()-1;i>=0;i--)
这两种看似写法一样 但是内部在执行时 队列长度发生变化 循环一执行次数也发生变化 而循环二只会初始化一次 值不会发生变化
/* 由beginword 变到endword 每次中间单词必须要在单词表中
* 求变化最少的长度 (其实单词和终止单词也算)
* 这个过程像迷宫搜索 只不过不是在四个方向而是在26个方向 即 对每个字符可能情况搜索
* 由于是求最短路径 因此用记录层数的bfs 可以用哨兵或者记录队列长度的方法
*
* */
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
// 用set记录单词便于查找
unordered_set<string> dict(wordList.begin(), wordList.end());
if(dict.count(endWord)==0) return 0;
queue<string> q;
q.push(beginWord);
int h=0;
while(!q.empty()){
// 以下循环每次处理一层
int size = q.size();
for(int i=0;i<size;i++){
string tmp = q.front();q.pop();
if(tmp==endWord) return h+1;
for(int j=0;j<tmp.size();j++){
string news=tmp; // 重要
for(char c='a';c<='z';c++){
news[j] = c;
if(news==tmp) continue;
auto it = dict.find(news);
if(it!=dict.end()){
dict.erase(news);
//cout<<news<<" ";
q.push(news);
}
}
}
}
h++;
//cout<<"one layer";
}
return 0;
}
};