Question:
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,
start =
end =
dict =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
As one shortest transformation is
return its length
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
,return its length
5
.- 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) {
if (start.size() != end.size())
return 0;
if (start.empty() || end.empty())
return 1;
if (dict.size() == 0)
return 0;
int distance = 1; //!important
queue<string> queToPush, queToPop;
queToPop.push(start);
dict.erase(start);
while (dict.size() > 0 && !queToPop.empty())
{
while (!queToPop.empty())
{
string str(queToPop.front());
queToPop.pop(); //!important
for (int i = 0; i < str.size(); i++)
{
char temp = str[i];
for (char j = 'a'; j <= 'z'; j++)
{
if (j != temp){
str[i] = j;
if (str == end)
return distance + 1;
if (dict.count(str) > 0)
{
queToPush.push(str);
dict.erase(str); //delete corresponding element in dict in case of loop
}
}
}
str[i] = temp;
}
}
swap(queToPush, queToPop);
distance++;
}
return 0;
}
};
No comments:
Post a Comment