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.
int ladderLength(string start, string end, set<string> &dict)
{
if (start == "" || end == "")
return 0;
queue<string> q;
q.push(start);
q.push("0");
unordered_set<string> s;
s.insert(start);
int ans = 0;
int len = start.length();
while(!q.empty())
{
string str = q.front();
q.pop();
if (str == "0")
{
if (q.empty())
{
return 0;
}
++ans;
q.push("0");
continue;
}
if (str == end)
{
++ans;
return ans;
}
bool found = false;
for (int i = 0; i < len; ++i)
{
char ch = str[i];
string newStr = str;
for (int j = 0; j < 26; ++j)
{
char newCh = 'a' + j;
if (ch != newCh)
{
newStr[i] = newCh;
if (s.find(newStr) == s.end() && dict.find(newStr) != dict.end())
{
s.insert(newStr);
q.push(newStr);
}
}
}
}
}
return 0;
}