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队列之间用空串”“来标示层与层的间隔，每次碰到层的结尾，遍历深度+1。进入下一层。

class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(start.size() == 0 || end.size() == 0) return 0;

queue<string> wordQ;
wordQ.push(start);
wordQ.push("");
int path = 1;

while(!wordQ.empty())
{
string str = wordQ.front();
wordQ.pop();

if(str != "")
{
int len = str.size();
for(int i = 0; i < len; i++)
{
char tmp = str[i];

for(char c = 'a'; c <= 'z'; c++)
{
if(c == tmp) continue;
str[i] = c;
if(str == end) return path + 1; //假设改变后的单词等于end 返回path+1
if(dict.find(str) != dict.end())
{
wordQ.push(str);
dict.erase(str);   //字典内删除这个词 防止重复走
}
}
str[i] = tmp;  //重置回原来的单词
}
}
else if(!wordQ.empty())
{
//到达当前层的结尾。并且不是最后一层的结尾
path++;
wordQ.push("");
}
}
return 0;
}
};