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.
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
queue<string> nodeQ;
queue<int> depthQ;
nodeQ.push(start);
depthQ.push(0);
while(!nodeQ.empty())
{
string cur = nodeQ.front();
nodeQ.pop();
int depth = depthQ.front();
depthQ.pop();
for(int i = 0; i < cur.size(); i++)
{
string tmp = cur;
for(char a = 'a'; a < 'z'; a++)
{
tmp[i] = a;
if(cur == end)
return depth + 1;
else if(dict.find(tmp) != dict.end())
{
nodeQ.push(tmp);
depthQ.push(depth + 1);
dict.erase(tmp);
}
}
}
}
return 0;
}
};
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
queue<string> startSet[2];
int result = 2;
int flip = 0;
startSet[flip].push(start);
while(!startSet[flip].empty())
{
string temp = startSet[flip].front();
startSet[flip].pop();
if(findInDic(temp, dict, startSet[1-flip], end))
return result;
if(startSet[flip].empty())
{
flip = 1-flip;
result++;
}
}
return 0;
}
private:
bool findInDic(string target, unordered_set<string> &dict, queue<string> &result, string end)
{
for(int i = 0; i < target.size(); i++)
{
for(char j = 'a'; j <= 'z'; j++)
{
string temp = target;
temp[i] = j;
if(temp == end)
return true;
if(dict.find(temp) != dict.end())
{
result.push(temp);
dict.erase(temp);
}
}
}
return false;
}
};