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:
// BFS
bool tryGetNextStrings(string curString, string destString, unordered_set<string> &dict, list<string> &nextList, set<string> &visitedDic)
{
int len = curString.size();
for (int i=0; i<len; i++)
{
char curChar = curString.at(i); //get char one by one
for (char c='a'; c !='z'; c++)
{
string tmpString = curString; //try new char in that position
if (c != curChar)
{
tmpString.at(i) = c;
if (tmpString == destString)
{
return true;
}
if (visitedDic.find(tmpString) != visitedDic.end())
{
continue;
}
if (dict.find(tmpString) != dict.end())
{
nextList.push_back(tmpString);
visitedDic.insert(tmpString);
}
}
}
}
return false;
}
int ladderLength(string start, string end, unordered_set<string> &dict) {
if (start == end)
return 0;
list<string> preList;
set<string> visitedDic;
int count = 0;
preList.push_back(start);
visitedDic.insert(start);
while (preList.size() > 0)
{
list<string> nextList;
while (preList.size() > 0)
{
count++;
string curString = preList.front();
if (tryGetNextStrings(curString, end, dict, nextList, visitedDic))
{
return count;
}
preList.erase(preList.begin());
}
preList = nextList;
}
return 0;
}
};
class Solution {
public:
// BFS
bool tryGetNextStrings(string curString, string destString, unordered_set<string> &dict, list<string> &nextList)
{
int len = curString.size();
for (int i=0; i<len; i++)
{
char curChar = curString.at(i); //get char one by one
for (char c='a'; c !='z'; c++)
{
string tmpString = curString; //try new char in that position
if (c != curChar)
{
tmpString.at(i) = c;
if (tmpString == destString)
{
return true;
}
if (dict.find(tmpString) != dict.end())
{
nextList.push_back(tmpString);
dict.erase(tmpString); // very strange, we need to delete the the element in dic
}
}
}
}
return false;
}
int ladderLength(string start, string end, unordered_set<string> &dict) {
if (start == end)
return 0;
list<string> preList;
int count = 1;
preList.push_back(start);
while (dict.size() > 0 && preList.size() > 0)
{
list<string> nextList;
count++;
while (preList.size() > 0)
{
string curString = preList.front();
if (tryGetNextStrings(curString, end, dict, nextList))
{
return count;
}
preList.erase(preList.begin());
}
preList = nextList;
}
return 0;
}
};